I want to convert string to date in java [duplicate]
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?
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
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss.SS");
hour = simpleDateFormat.parse(a);
System.out.println(simpleDateFormat.format(hour));