Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Converting Retrieved TimeStamp to Instant Gives Wrong Day

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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";
  • EEE three letter day of week
  • LLL three letter month
  • dd integer day
  • HH:mm:ss time using 24 hour clock
  • z time zone name (CST)
  • yyyy year
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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading