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?
tl;dr
Use only java.time classes. Never use the legacy
Date
/Calendar
classes.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:
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
.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.
If you want the current moment as seen in a particular time zone, use
ZonedDateTime
.If you want the current moment as seen in UTC, use
Instant
.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?