Convert String of this "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" format to LocalDate

viren shah :

I want to convert the string date (with timezone specified) to LocalDate.

String format = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
String date = "2019-08-31T17:00:00.000-07:00";

System.out.println("LocalDate: " + LocalDate.parse(date, DateTimeFormatter.ofPattern(format)));
System.out.println("Date: " + new SimpleDateFormat(format).parse(date));

and output of the above code is

LocalDate: 2019-08-31
Date: Sun Sep 01 05:30:00 IST 2019

I am not able to get the same result that got from SimpleDateFormat. I want 2019-09-01 in LocalDate.

Sweeper :

Note that the old Date class represents a point in time, not a local date. It just so happens that Date.toString outputs the string as if it is in the system time zone.

The java.time API forces you to think more deeply about what you want. It provides you different types to represent different temporal concepts. LocalDate.parse will only interpret the "local date" part of the string.

Your date string represents an OffsetDateTime, so you should use OffsetDateTime.parse. Now you have a LocalDateTime plus a ZoneOffset. To make it 09-01, you have to change its zone, while keeping it the same instant, which can be done with atZoneSameInstant, and then get the local date part of it:

System.out.println("LocalDate: " +
        OffsetDateTime.parse(date, DateTimeFormatter.ofPattern(format))
                .atZoneSameInstant(ZoneOffset.systemDefault())
                .toLocalDate());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=323893&siteId=1