简体   繁体   中英

How to compare two dates along with time in java

I have two Date<\/code><\/strong> objects with the below format.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String matchDateTime = sdf.parse("2014-01-16T10:25:00");
Date matchDateTime = null;

try {
    matchDateTime = sdf.parse(newMatchDateTimeString);
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

// get the current date
Date currenthDateTime = null;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date dt = new Date();
String currentDateTimeString = dateFormat.format(dt);
Log.v("CCCCCurrent DDDate String is:", "" + currentDateTimeString);

try {                   
    currenthDateTime = sdf.parse(currentDateTimeString);
} catch (ParseException e) {
    // TODO Auto-generated catch block 
    e.printStackTrace();
}

Since Date<\/code> implements Comparable<Date><\/code> , it is as easy as:

date1.compareTo(date2);

An Alternative is....

Date d = new Date();
long l = d.getTime();

Use compareTo()<\/code><\/strong><\/a>

a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.

if(date1.compareTo(date2)>0) 

An alternative is Joda-Time<\/a> .

DateTime date = new DateTime(new Date());
date.isBeforeNow();
or
date.isAfterNow();
 // Get calendar set to the current date and time
Calendar cal = Calendar.getInstance();

// Set time of calendar to 18:00
cal.set(Calendar.HOUR_OF_DAY, 18);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

// Check if current time is after 18:00 today
boolean afterSix = Calendar.getInstance().after(cal);

if (afterSix) {
    System.out.println("Go home, it's after 6 PM!");
}
else {
    System.out.println("Hello!");
}

The other answers are generally correct and all outdated. Do use java.time, the modern Java date and time API, for your date and time work. With java.time your job has also become a lot easier compared to the situation when this question was asked in February 2014.

    String dateTimeString = "2014-01-16T10:25:00";
    LocalDateTime dateTime = LocalDateTime.parse(dateTimeString);
    LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());

    if (dateTime.isBefore(now)) {
        System.out.println(dateTimeString + " is in the past");
    } else if (dateTime.isAfter(now)) {
        System.out.println(dateTimeString + " is in the future");
    } else {
        System.out.println(dateTimeString + " is now");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM