Home > Software design >  LocalDateTime.now() doesnt give the system local time
LocalDateTime.now() doesnt give the system local time

Time:08-16

So I have a problem with LocalDateTime.now() returning the wrong time(off by 2 hours, the same as the timezone) When I check the linux server the date command returns the right time, running hwclock -r shows the right time too.

This is from the command timedatectl https://gyazo.com/9c70f5719a03492e0d7fdff3128f2f1d

The local time is what is shown in date and hwclock -r but LocalDateTime.now() returns the universal time/RTC time

Even MySQL shows the local time (doing SELECT NOW())

Any ideas to why/what I have to change to make LocalDateTime.now() return the correct time - I know I could use a ZonedTimeZone but this is not only for my own projects but it also applies to other java programs/plugins running on the machine that I don't have control over

CodePudding user response:

With the help from @OleV.V I got it working with the jvm argument -Duser.timezone=Europe/Paris

For example:

java -Duser.timezone=Europe/Paris -jar TestProject.jar

CodePudding user response:

Wrong class

I cannot imagine a situation where calling LocalDateTime.now() is the right thing to do.

The LocalDateTime class cannot represent a moment, a specific point on the timeline, as it lacks the context of a time zone or offset from UTC.

When you call the LocalDateTime.now method, the JVM’s current default time zone is implicitly applied. But keep in mind that the current default can be changed at runtime, at any moment, by any code in any app within that JVM.

Simply put, you are using the wrong class.

ZonedDateTime

To capture the current moment as seen in a particular time zone, use ZonedDateTime class.

ZoneId z = ZoneId.of( "Europe/Paris" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
  • Related