24

I have two Date 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();
}

Now I want to compare the above two dates along with time. How should I compare in Java.

Thanks

Milad Rashidi
  • 1,296
  • 4
  • 22
  • 40
user2636874
  • 889
  • 4
  • 15
  • 36
  • possible duplicate of [How to compare dates in Java?](http://stackoverflow.com/questions/2592501/how-to-compare-dates-in-java) – Basil Bourque Oct 19 '14 at 18:51

6 Answers6

43

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

date1.compareTo(date2);

As the Comparable contract stipulates, it will return a negative integer/zero/positive integer if date1 is considered less than/the same as/greater than date2 respectively (ie, before/same/after in this case).

Note that Date has also .after() and .before() methods which will return booleans instead.

fge
  • 119,121
  • 33
  • 254
  • 329
  • Can I somehow get the duration. Something like 2 days or 16 hours...something like that using the `comapreTo` method? – praxmon Feb 23 '15 at 11:03
  • @PrakharMohanSrivastava no you can't; you'll have to diff the milliseconds. You can use `TimeUnit` to help you "fractionize" the resulting difference afterwards – fge Feb 23 '15 at 11:16
9

An Alternative is....

Convert both dates into milliseconds as below

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

Now compare both long values

Vibin
  • 109
  • 1
  • 7
6

Use compareTo()

Return Values

0 if the argument Date is equal to this Date; 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.

Like

if(date1.compareTo(date2)>0) 
Nambi
  • 11,944
  • 3
  • 37
  • 49
3

An alternative is Joda-Time.

Use DateTime

DateTime date = new DateTime(new Date());
date.isBeforeNow();
or
date.isAfterNow();
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
MaximeF
  • 4,913
  • 4
  • 37
  • 51
2
 // 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!");
}
sujith s
  • 864
  • 11
  • 20
2

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");
    }

When running in 2020 output from this snippet is:

2014-01-16T10:25:00 is in the past

Since your string doesn’t inform of us any time zone or UTC offset, we need to know what was understood. The code above uses the device’ time zone setting. For a known time zone use like for example ZoneId.of("Asia/Ulaanbaatar"). For UTC specify ZoneOffset.UTC.

I am exploiting the fact that your string is in ISO 8601 format. The classes of java.time parse the most common ISO 8601 variants without us having to give any formatter.

Question: For Android development doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161