Home > Software engineering >  Spring Boot Java Time zone Bangkok (GMT 8) or another time zone with GMT 8 with ZonedDateTime using
Spring Boot Java Time zone Bangkok (GMT 8) or another time zone with GMT 8 with ZonedDateTime using

Time:10-27

Good day, it's not some errors. But can someone explain to me what happened here?

I'am using free sql database with Spring framework so basically my sql database was on the cloud. Then I'm inserted date time value to my database using my local time zone (Indonesia (GMT 8)). But the time zone is not correct with my time zone even I'm already used localdatetime.now()

This was the case :

Set up my localdatetime zone

LocalDateTime ldt = LocalDateTime.now();

Using my system default time zone

ZonedDateTime zdt = ZonedDateTime.of(ldt, ZoneId.systemDefault());

This is the output (My time zone showing at 22:47) '2022-10-26 16:05:52'

Using (GMT 8)

ZonedDateTime gmt = zdt.withZoneSameInstant(ZoneId.of("GMT 8"));

This is the output (My time zone showing at 23:10) ''2022-10-26 17:10:30''

Using (GMT 12)

This is the output (My time zone showing at 23:15) ''2022-10-26 21:15:47''

Using (GMT 14) I'm even dont know anymore are this time zone literally correct

This is the output (My time zone showing at 23:20) ''2022-10-26 23:20:47'' This was my time zone (basically, this is the right one)

Using GMT 14 was right according to my own clock, but my time zone (Indonesia, GMT 8). Then I'm checked to my server where my database are located at the cloud, then I found it at Asia Pacific.

This is my lines of code :

LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime zdt = ZonedDateTime.of(ldt, ZoneId.systemDefault());
ZonedDateTime gmt = zdt.withZoneSameInstant(ZoneId.of("GMT 14"));
Timestamp timestamp = Timestamp.valueOf(gmt.toLocalDateTime());
transaction.setDate(timestamp);
transactionServices.saveTransaction(transaction);

So are this happened because where my database are located or because something else? Can someone explain so I can improve my code.

I'am expecting using GMT 8 not GMT 14, I'm affraid this can be a problem when this application is produced.

CodePudding user response:

LocalDateTime.now()

I cannot imagine a scenario where calling LocalDateTime.now is the right thing to do.

ZonedDateTime zdt = ZonedDateTime.of(ldt, ZoneId.systemDefault());

Skip the LocalDateTime variable ldt. Just ask ZonedDateTime to capture the current moment as seen in your desired time zone.

ZoneId z = ZonedId.systemDefault() ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;

ZonedDateTime gmt = zdt.withZoneSameInstant(ZoneId.of("GMT 8"));

For an offset, use the subclass ZoneOffset rather than ZoneID.

ZoneOffset offset = ZoneOffset.of( 8 ) ;

And, this code does not make sense in couple ways. Firstly, if you want to represent a moment as seen through an offset, use OffsetDateTime.

OffsetDateTime odt = OffsetDateTime.now( offset ) ;

Secondly, you should generally

  • Related