Biscuit128 Biscuit128 - 1 year ago 93
Java Question

Compare if a date is less than 24 hours before

I am trying to compare two calendars in java to decide if one of them is >= 24 hours ago. I am unsure on the best approach to accomplish this.

//get todays date
Date today = new Date();
Calendar currentDate = Calendar.getInstance();

//get last update date
Date lastUpdate = profile.getDateLastUpdated().get(owner);
Calendar lastUpdatedCalendar = Calendar.getInstance();

//compare that last hotted was < 24 hrs ago from today?

Answer Source

you could use Date.getTime(), here's an example:

public final static long MILLIS_PER_DAY = 24 * 60 * 60 * 1000L;
public static void main(String args[]) throws Exception {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date date1 = sdf.parse("2009-12-31");
    Date date2 = sdf.parse("2010-01-31");

    boolean moreThanDay = Math.abs(date1.getTime() - date2.getTime()) > MILLIS_PER_DAY;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download