Search code examples
javajava-timelocaldatetime

Get a LocalDateTime object from a given string?


"2021-09-17 11:48:06 UTC"

I want to parse the following string and create a LocalDateTime object or an Instant

I know you can write something like this

String dateTime = "2021-09-17 11:48:06 UTC";
LocalDateTime dt = LocalDateTime.parse(dateTime,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

How do I deal with the UTC part in the string?


Solution

  • "2021-09-17 11:48:06 UTC" isn't a local date time: it's a date time, because it has a time zone. And because your time has a time zone, it doesn't match your pattern, which doesn't.

    If your time strings always end with exactly "UTC", you can make that a literal in the pattern:

    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss 'UTC'");
    

    If you need to handle other time zones than UTC, you can use z:

    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");
    

    but note that this is for parsing a zoned date time; from that, you can extract the local date time:

    ZonedDateTime zdt = ZonedDateTime.parse(dateTime,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");
    LocalDateTime ldt =z dt.toLocalDateTime();