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
  • 100,966
  • 191
  • 140
  • 197
  • 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

3

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
  • 17,687
  • 10
  • 38
  • 51
  • I just only want to get 20:55:45.26 –  Jan 14 '22 at 08:33
  • Then change the pattern in the `DateTimeFormatter` to `HH:mm:ss.SS` (last part of my code example). – deHaar Jan 14 '22 at 08:38
  • Dear Sir, ,it works but I want to get this output with using Date type. How can I do that? Thank you for your help. –  Jan 14 '22 at 08:42
  • Well, that is an old and outdated api, but if you really want to, then use the solution by @Константин, I think he just corrected the pattern. – deHaar Jan 14 '22 at 08:43
  • When I try that output looks like 08:55:13.743 –  Jan 14 '22 at 08:47
1
  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss.SS");
  hour = simpleDateFormat.parse(a);

  System.out.println(simpleDateFormat.format(hour));
Cookie
  • 193
  • 7
  • output is : 08:55:13.743 –  Jan 14 '22 at 08:37
  • Not anymore, @OguzhanOzturk… The pattern has changed from lower case (`hh`, 12h format) to upper case (`HH`= 24h format) – deHaar Jan 14 '22 at 10:28
  • My input is 20:50:45.268743 but the output is 20:55:13.743. Where does the difference become? –  Jan 14 '22 at 11:35