user3205610
user3205610

Reputation: 51

How to convert 'dd/mm/yyyy hh:mm:ss am/pm' to hh:mm:ss (without am or pm) in java?

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

Answers (3)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79005

java.time

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

Online Demo

Learn about the modern date-time API from Trail: Date Time

Upvotes: 2

vishvaraj
vishvaraj

Reputation: 1

Use ("dd/MM/yyyy hh:mm:ss tt") for AM/PM

Upvotes: -1

Polyethylene
Polyethylene

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

Related Questions