I'm using LocalDateTime.now()
to get the date and time of system, but the time is with an hour in past.
If the system has 14:52, now()
return 13:52.
OS of system is Windows 10.
LocalDateTime
is wrong classNever use LocalDateTime
to represent a moment, a specific point on the timeline. Purposely lacking any concept of time zone or offset-from-UTC, this type represents potential moments along the range of about 26-27 hours (range of time zones around the globe).
To get the current moment in UTC, use Instant
.
Instant instant = Instant.now() ;
To get the current moment as seen in the wall-clock time used by people in a particular region (a time zone), use ZonedDateTime
.
I suspect your problem is that your expected time zone was not actually the current default zone when your code ran. In your code you failed to specify a time zone, and so the JVM’s current default time zone was silently applied. You could verify the current default by calling ZoneId.systemDefault().toString()
.
Relying implicitly on the JVM’s current default time zone is a bad practice in my opinion. Better to always specify your desired/expected time zone explicitly. Always pass the optional ZoneId
argument.
ZoneId z = ZoneId.of( "America/Montreal" ) ; // Or get the JVM’s current default time zone: ZoneId.systemDefault()
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
java.util.TimeZone.setDefault()
is the method in java which is used to set the timeZone
in java. It takes TimeZone
as input parameter. You can get an object of TimeZone
by TimeZone.getTimeZone("id");
There are different id for different time Zone. For example id for me is "Asia/Calcutta" so passing that will return me the TimeZone
of my region.
TimeZone tzone = TimeZone.getTimeZone("Asia/Calcutta");
TimeZone.setDefault(tzone);
Above line will change my timezone to calcutta region.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With