I’ve made a simple method which is used to convert a timestamp retrieved from a database into a LocalDate. However for some reason I keep getting the wrong day in the conversion. I’ve shared the code below.
private LocalDate getLocalDateFromTimeStamp(Row row, String key){
return LocalDate.parse(row.getTimestamp(key).toInstant().atZome(ZoneOffset.UTC).toLocalDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
}
So the date I’m expecting is 2022-12-21 but what I get is 2022-12-22.
When I debug and check what
row.getTimestamp(key)
gets me it’s "Wed Dec 21 20:47:46 CST 2022" which is what I expect.
When I check what
row.getTimestamp(key).toInstant()
does, I get "2022-12-22T02:47:46:299Z". And I think this is where the problem is popping up and I’m not sure why it’s happening. The LocalDate that’s returned by the method is "2022-12-22".
If anyone could shine a light on this I’d really appreciate it as I’m lost as to why this is happening.
>Solution :
Try it like this. Check out DateTimeFormatter for details on the following arguments.
String date = "Wed Dec 21 20:47:46 CST 2022";
EEEthree letter day of weekLLLthree letter monthddinteger dayHH:mm:sstime using 24 hour clockztime zone name (CST)yyyyyear
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE LLL dd HH:mm:ss z yyyy");
LocalDate dt = LocalDateTime.parse(date, dtf).toLocalDate();
System.out.println(dt);
prints
2022-12-21