2

I have a string like "hh:mm:ss.SSSSSS" and I want to convert this string to Date and I want to get "hh:mm:ss.SS". However, when I compile my code, it still gives the day month year time and timezone like "Thu Jan 01 10:50:55 TRT 1970". I attached my code below to the text.

String a = "20:50:45.268743";
Date hour;
try {
    hour = new SimpleDateFormat("hh:mm:ss.SS").parse(a);
    System.out.println(hour);
} catch(ParseException e) {
    e.printStackTrace();
}

My output is hu Jan 01 20:55:13 TRT 1970 but I want to get 20:55:45.26.
Is there anyone who can help me about this situation?

Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175
  • A `Date` itself has no format (its `toString()` has a fixed format), if you want to *print* the date with a specific format, you need to use `SimpleDateFormat`. As an aside, it is highly recommended to stop using `Date`, and instead switch to the `java.time` classes. – Mark Rotteveel Jan 15 '22 at 09:51

2 Answers2

4

Hint: Your example String is of the format HH:mm:ss.SSSSSS, not "hh:mm:ss.SSSSSS.


If you want to parse and format time of day exclusively (independent from a day/date), then use a java.time.LocalTime for that:

public static void main(String[] args) throws IOException {
    String a = "20:50:45.268743";
    // parse the String to a class representing a time of day
    LocalTime localTime = LocalTime.parse(a);
    // print it
    System.out.println(localTime);
    // or print it in a different format
    System.out.println(
            localTime.format(
                    DateTimeFormatter.ofPattern("hh:mm:ss a", Locale.ENGLISH)));
    // or print it exactly as desired
    System.out.println(
            localTime.format(
                    DateTimeFormatter.ofPattern("HH:mm:ss.SS", Locale.ENGLISH)));
}

Output is

20:50:45.268743
08:50:45 PM
20:50:45.26
deHaar
  • 14,698
  • 10
  • 35
  • 45
1
  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss.SS");
  hour = simpleDateFormat.parse(a);

  System.out.println(simpleDateFormat.format(hour));
Cookie
  • 193
  • 6