1

I'm using Hibernate 5 & MySQL.

This is what is getting saved into the database: 2018-03-11 06:26:47.336 I don't think this is 24 hour format, but then how do I see AM/PM? And how do I save the time in 24 hour format?

Running SELECT @@global.time_zone; in MySQL shows me: +00:00 So I think I'm set for accepting UTC time? This is how I set my pojo's field for setting time:

Clock clock = Clock.systemUTC();        
LocalDateTime userCreated = LocalDateTime.now(clock);

It accepts LocalDateTime. But what I get back from database when I query is: u1.getUserCreated(): 2018-03-11T01:26:47.336 And when I try to convert the time into zone specific, I get the below:

ZonedDateTime z1 = ZonedDateTime.of(u1.getUserCreated(), ZoneId.of("America/New_York"));
System.out.println("z1: " + z1); 
// z1: 2018-03-11T01:26:47.336-05:00[America/New_York]

But it really should be: 9:26:47.336 PM (21:26:47.336) As you can see on this site: http://www.timebie.com/std/utc.php

Noman
  • 887
  • 1
  • 15
  • 34

1 Answers1

3

You're just not converting correctly. Your LocalDateTime represents the wall-clock time in the UTC time zone. Not in the New York time zone. So yo need to transform it to a ZonedDateTime in UTC::

ZonedDateTime utcDateTime = u1.getUserCreated().atZone(ZoneOffset.UTC);

Then, if you want to get a ZonedDateTime for the same instant, but in the New York timezone, then, well, just do that:

ZonedDateTime newYorkDateTime = utcDateTime.withZoneSameInstant(ZoneId.of("America/New_York"));
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Yeah, thank you, just figured it out a minute ago too. But could you answer my other questions too please? Regarding AM, PM & why is the time being set in the database not 24 hour format? – Noman Mar 11 '18 at 22:47
  • 2
    Dates stored in the database have no format. The format depends on how you (or the software used to look at the database content) print the stored date. – JB Nizet Mar 11 '18 at 22:51
  • It shows me 24 hour format should be going into the database: userCreated: 2018-03-11T22:52:29.348 – Noman Mar 11 '18 at 22:53
  • 1
    @Noman As JB Nizet commented, a date-time value is stored in the database in some collection of bits and bytes, not as text. So a date-time has no “format”. Your tools and middleware may generate text to represent the date-time value. Many of those tools are designed poorly with regard to the choice of format of such text. – Basil Bourque Mar 12 '18 at 05:44