Class Date
Prior to JDK 1.1, the class Date had two additional functions. It allowed the interpretation of dates as year, month, day, hour, minute, and second values. It also allowed the formatting and parsing of date strings. Unfortunately, the API for these functions was not amenable to internationalization. As of JDK 1.1, the Calendar class should be used to convert between dates and time fields and the DateFormat class should be used to format and parse date strings. The corresponding methods in Date are deprecated.
Although the Date class is intended to reflect coordinated universal time (UTC), it may not do so exactly, depending on the host environment of the Java Virtual Machine. Nearly all modern operating systems assume that 1 day = 24 × 60 × 60 = 86400 seconds in all cases. In UTC, however, about once every year or two there is an extra second, called a «leap second.» The leap second is always added as the last second of the day, and always on December 31 or June 30. For example, the last minute of the year 1995 was 61 seconds long, thanks to an added leap second. Most computer clocks are not accurate enough to be able to reflect the leap-second distinction.
Some computer standards are defined in terms of Greenwich mean time (GMT), which is equivalent to universal time (UT). GMT is the «civil» name for the standard; UT is the «scientific» name for the same standard. The distinction between UTC and UT is that UTC is based on an atomic clock and UT is based on astronomical observations, which for all practical purposes is an invisibly fine hair to split. Because the earth’s rotation is not uniform (it slows down and speeds up in complicated ways), UT does not always flow uniformly. Leap seconds are introduced as needed into UTC so as to keep UTC within 0.9 seconds of UT1, which is a version of UT with certain corrections applied. There are other time and date systems as well; for example, the time scale used by the satellite-based global positioning system (GPS) is synchronized to UTC but is not adjusted for leap seconds. An interesting source of further information is the United States Naval Observatory (USNO):
and the material regarding «Systems of Time» at:
which has descriptions of various different time systems including UT, UT1, and UTC.
- A year y is represented by the integer y — 1900 .
- A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.
- A date (day of month) is represented by an integer from 1 to 31 in the usual manner.
- An hour is represented by an integer from 0 to 23. Thus, the hour from midnight to 1 a.m. is hour 0, and the hour from noon to 1 p.m. is hour 12.
- A minute is represented by an integer from 0 to 59 in the usual manner.
- A second is represented by an integer from 0 to 61; the values 60 and 61 occur only for leap seconds and even then only in Java implementations that actually track leap seconds correctly. Because of the manner in which leap seconds are currently introduced, it is extremely unlikely that two leap seconds will occur in the same minute, but this specification follows the date and time conventions for ISO C.
In all cases, arguments given to methods for these purposes need not fall within the indicated ranges; for example, a date may be specified as January 32 and is interpreted as meaning February 1.
Constructor Summary
Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date) .
As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date, hrs, min) or GregorianCalendar(year + 1900, month, date, hrs, min) .
As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date, hrs, min, sec) or GregorianCalendar(year + 1900, month, date, hrs, min, sec) .
Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as «the epoch», namely January 1, 1970, 00:00:00 GMT.
Compare Two Dates in Java
Learn to compare two given dates in Java to find out which date is earlier and which is later in the universal timeline. We will see date comparison examples using the following classes:
- LocalDate , LocalDateTime and ZonedDateTime classes from Java 8
- Date and Calendar (till Java 7)
1. Date Comparison since Java 8
- java.time.LocalDate – Only the date , without time and timezone.
- java.time.LocalDateTime – Only date and time, without timezone
- java.time.ZonedDateTime – Date and time with timezone.
- java.time.Instant – seconds passed since the epoch (midnight of January 1, 1970 UTC)
All the above classes have methods for comparing two instances of themselves i.e. isAfter() , isBefore() , isEqual() and compareTo() .
- date1.isAfter( date2 ) – It returns true is date1 comes after date2; else false .
- date1.isBefore( date2 ) – It returns true is date1 comes before date2; else false .
- date1.isEqual( date2 ) – It returns true is date1 is equal to date2; else false .
- date1.compareTo( date2 ) – It returns ‘positive number’ is date1 comes after date2; else ‘negative number’. A value ‘0’ means both dates are equal.
It is very important to note that :
- If we want to compare only the date part and do not care about which part of time it is – then use LocalDate instances.
- LocalDateTime and ZonedDateTime compare time part as well, so even if the day they represent is same calendar day, if time is not same then they are not equal.
- Use toLocalDate() to get the date part from LocalDateTime and ZonedDateTime instances.
Java program to compare two instances of the LocalDate class.
LocalDate today = LocalDate.now(); LocalDate anotherDay = LocalDate.of(2018, 01, 10); System.out.println(today.isEqual(anotherDay)); //false System.out.println(today.isAfter(anotherDay)); //true System.out.println(today.isBefore(anotherDay)); //false int diff = today.compareTo(anotherDay); if(diff > 0) < System.out.println(today + " is greater than " + anotherDay); >else if (diff < 0) < System.out.println(today + " is less than " + anotherDay); >else
Java program to compare to LocalDateTime instances.
LocalDateTime instance = LocalDateTime.now(); // To have different time part in both instances Thread.currentThread().sleep(100); LocalDateTime anotherInstance = LocalDateTime.now(); // Compare only date part boolean isEqual = instance.toLocalDate() .isEqual(anotherInstance.toLocalDate()); System.out.println(isEqual); //true // Compare date and time parts System.out.println(instance.isEqual(anotherInstance)); // false System.out.println(instance.isAfter(anotherInstance)); // false System.out.println(instance.isBefore(anotherInstance)); // true
Java program to compare two ZonedDateTime instances. Note that the comparison using the compareTo() is based first on the instant, then on the local date-time, then on the zone ID, then on the chronology. In other words, it compares all the date and time fields in both instances. So, if two instances present exactly the same time in the universal timeline, but they are in the different timezones then compareTo() method will not return zero.
To correctly compare the two ZonedDateTime with respect to the epoch time, compare the zdt.toInstant() field. Or we can use isBefore(), isEqual() or isAfter() methods that compare the epoch seconds.
ZonedDateTime now = ZonedDateTime.now(); //If we want to convert to the same instant in diferent timezone ZonedDateTime nowInUTC = now.withZoneSameInstant(ZoneId.of("UTC")); ZonedDateTime zdtInUTC = ZonedDateTime .parse("2022-02-15T11:21:12.123+05:30[UTC]"); long difference = nowInUTC.toInstant() .compareTo(zdtInUTC.toInstant()); if (difference > 0) < System.out.println("zoneddatetime1 >zoneddatetime2"); > else if (difference < 0) < System.out.println("zoneddatetime1 < zoneddatetime2"); >else
2. Date Comparison till Java 7
The most used date classes till Java 7 were:
Both, Date and Calendar classes have methods before() , after() , equals() and compareTo() methods for date comparison purposes.
- date1.after( date2 ) – It returns true is date1 comes after date2; else false .
- date1.before( date2 ) – It returns true is date1 comes before date2; else false .
- date1.equals( date2 ) – It returns true is date1 and date2 are equal; else false .
- date1.compareTo( date2 ) – It returns ‘positive number’ is date1 comes after date2; else ‘negative number’. A value ‘0’ means both dates are equal.
Note: Both, Date and Calendar classes have time part and above methods use it for comparing. So, if you want to compare only date part and do not care time part of it, then you need to extract day/month/year from other instances are compare them one to one.
2.3. Comparing Date Instances
In the given code, we first compare the two date instances including their time part.
Date date1 = new Date(); // To have different time part in both instances Thread.currentThread().sleep(100); Date date2 = new Date(); System.out.println(date1.equals(date2)); // false System.out.println(date1.after(date2)); // false System.out.println(date1.before(date2)); // true
Now we will compare both dates for only their date part excluding any time part associated with instances. We are using the Calendar class to extract the day, month and year information from the Date instance.
Date date1 = new Date(); Thread.currentThread().sleep(100); Date date2 = new Date(); int diff = compareDatePartOnly(date1, date2); if (diff > 0) < System.out.println(date1 + " is greater than " + date2); >else if (diff < 0) < System.out.println(date1 + " is less than " + date2); >else < System.out.println(date1 + " is equal to " + date2); >private static int compareDatePartOnly(final Date date1, final Date date2) < Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); cal1.setTime(date1); cal2.setTime(date2); int result = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR); if (result == 0) < result = cal1.get(Calendar.DAY_OF_YEAR) - cal2.get(Calendar.DAY_OF_YEAR); >return result; >