Date
Compare Date objects with after method
In this example we shall show you how to compare Date objects with after(Date when)
method of Date, that tests if a Date is after the specified one. To compare a Date object with another Date object, using after(Date when)
API method of Date one should perform the following steps:
- Use the simple
Date()
constructor, to allocate a Date object and initialize it so that it represents the time at which it is allocated, measured to the nearest millisecond. - Use
getInstance()
API method of Calendar to get a Calendar object, using the default time zone and locale. - Use
set(int field, int value)
API method of Calendar to set a value to the calendar object. The field is set toCalendar.YEAR
and the value is set to a past year in the example. - Get the Date object that represents this calendar’s time value, with millisecond offset from the January 1 1970 00:00:00.000 GMT, using
getTime()
API method of Calendar. - Use
after(Date when)
API method of Date. The method returns true if and only if the instant represented by this Date object is strictly later than the instant represented bywhen
, as in the example, and false otherwise.
Let’s take a look at the code snippet that follows.
package com.javacodegeeks.snippets.core; import java.util.Calendar; import java.util.Date; public class CompareDateObjectsWithAfterMethod { public static void main(String[] args) { Date now = new Date(); Calendar c = Calendar.getInstance(); c.set(Calendar.YEAR, 1990); Date past = c.getTime(); if (now.after(past)) { System.out.println(now + " is after " + past); } } }
Output:
Thu Oct 20 16:14:42 EEST 2011 is after Sat Oct 20 16:14:42 EET 1990
This was an example of how to compare Date objects with after(Date when) method of Date in Java.