Date(System.currentTimeInMillis) not working

149 views Asked by At

I wanted today's date using the date object so I passed System.currentTimeInMillis in Date() constructor but it returns the year as 121

Then I used Calendar class and it solved my problem, but why wasn't Date() class working in the first place?

1

There are 1 answers

0
Basil Bourque On

tl;dr

Use only java.time classes. Never use the legacy Date/Calendar classes.

java.time.LocalDate.now()

Avoid legacy date-time classes

You are using terrible date-time classes bundled with the earliest versions of Java. These classes were written by people who did not understand date-time handling, and who made very poor design choices.

Sun, Oracle, and the JCP community gave up on these classes years ago with the unanimous adoption of JSR 310. I suggest you give up on them as well. Use only the java.time classes for your date-time work.

121 + 1900 = 2021

➥ To answer your specific question: Among the many problems of these legacy classes is that the year is represented as being off by 1900. To quote the Javadoc:

A year y is represented by the integer y - 1900.

So adding 1900 to your year of 121 results in 2021. Mystery solved. But never mind, just move on to using java.time instead.

java.time

If you want only the date, without the time-of-day and without a time zone, use LocalDate.

LocalDate today = LocalDate.now() ;

Better to specify a desired/expected time zone through which to perceive the current date, rather than rely implicitly on the JVM’s current default time zone. For any given moment, the date varies around the globe by time zone, "tomorrow" in Tokyo Japan while still "yesterday" in Toledo Ohio US.

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
LocalDate today = LocalDate.now( z ) ;

If you want the current moment as seen in a particular time zone, use ZonedDateTime.

ZonedDateTime now = ZonedDateTime.now( z ) ;

If you want the current moment as seen in UTC, use Instant.

Instant now = Instant.now() ;

About java.time

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?