Home > Net >  How to convert a String data and time includin month name to Date object in Java?
How to convert a String data and time includin month name to Date object in Java?

Time:10-15

I want to convert the date in string to date object being the string "10h 57m 20s October 13 2020". How can be done? may replace firstly the h, m and s to get the format "10:57:20 October 13 2020"? As well, I tried the last format "10:57:20 October 13 2020" to get the date with DateTimeFormat and DateTimeFormatterBuilder() but is does not work with the month or it works but the hour coverts to 00:00:00.

Thanks

CodePudding user response:

java.time

I recommend that you use java.time, the modern Java date and time API, for your date and time work. Like Joop Eggen already wrote, put the letters that are part of your format in single quotes in the format pattern string:

private static final DateTimeFormatter FORMATTER
        = DateTimeFormatter.ofPattern("H'h' m'm' s's' MMMM d y", Locale.ENGLISH);

This will allow you to parse like this:

    String dateInString = "10h 57m 20s October 13 2020";
    LocalDateTime dateTime = LocalDateTime.parse(dateInString, FORMATTER);
    System.out.println(dateTime);

Output:

2020-10-13T10:57:20

You shouldn’t take any interest in the old-fashioned Date class. However, sometimes we need to pass a Date to a legacy API not yet upgraded to java.time. The conversion requires that we know the time zone assumed for the parsed date and time. For example:

    ZoneId zone = ZoneId.of("America/Tegucigalpa");
    Instant i = dateTime.atZone(zone).toInstant();
    Date oldfashionedDate = Date.from(i);
    System.out.println(oldfashionedDate);

Example output:

Tue Oct 13 10:57:20 CST 2020

Tutorial link

Oracle tutorial: Date Time explaining how to use java.time.

CodePudding user response:

You can place fixed letters in apostrophes.

"HH'h' mm'm' ss's' MMMM dd yyyy"

Furthermore hh is the 12 hour format to be combined wiht a AM/PM. HH is the 24 hour format.

Also the locale must be correct, maybe explicitly set. Here English.

  • Related