Reputation: 51
I want the convert the string like 1/15/2014 9:57:03 AM
or 1/15/2014 5:49:39 PM
to 9:57:03
and 17:49:39
Upvotes: 2
Views: 40388
Reputation: 79005
In March 2014, the modern Date-Time API supplanted the legacy date-time API. Since then, it has been strongly recommended to switch to java.time
, the modern date-time API.
Your date-time string does not have time-zone information; therefore, parse it to a LocalDateTime
using a DateTimeFormatter
. Then, format the obtained LocalDateTime
into a string using another DateTimeFormatter
with the desired format.
DateTimeFormatter parser = DateTimeFormatter.ofPattern("M/d/uuuu h:mm:ss a", Locale.ENGLISH);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("H:mm:ss", Locale.ENGLISH);
// Test
Stream.of(
"1/15/2014 9:57:03 AM",
"1/15/2014 5:49:39 PM"
).forEach(s -> {
LocalDateTime ldt = LocalDateTime.parse(s, parser);
String formatted = ldt.format(formatter);
System.out.println(formatted);
});
Output:
9:57:03
17:49:39
Learn about the modern date-time API from Trail: Date Time
Upvotes: 2
Reputation: 187
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a", Locale.US);
Date date = format.parse("1/15/2014 9:57:03 AM");
format = new SimpleDateFormat("HH:mm:ss");
String dateString = format.format(date);
BTW, use Google next time
Upvotes: 10