How to compare two dates in Android

  • Written by  Clive

Comparing two dates in Android

I was busy doing some Android coding and needed to compare two dates. The result of the comparison had to show whether the dates were the same or whether one was greater than the other (or smaller). Having stored the dates as an integer in a SQLite database, I extracted and converted them into long objects. It was these long objects that I had to compare. 

As the long objects were accurate time stamps in milliseconds (including hours, minutes, seconds, and milliseconds), this posed a problem when comparing the dates as the same dates would not register as being equal if they differed by even a millisecond! The solution was to first convert them into a format that only represented the day, month and year.



The two long dates were date1Long and date2Long.

I created two Calendar objects, setting each to one of the two dates. Bear in mind that these calendar objects contained the precise instant in time for each date, down to the last millisecond. I now needed to extract only the day, month and year for each of the dates out of calendar objects.

The day, month and year are extracted as integer values which are then converted to strings by simply using String.valueOf().

Android date conversion to Calendar object

Use SimpleDateFormat to get the Date objects used in the comparison

Once we have these strings, we can use the SimpleDateFormat class to parse these values into Date objects, formatted to our requirements by passing a pattern string, yyyy-MM-dd as the parameter. It’s these date objects that we need to make the comparison.

Comparing Android dates using SimpleDateFormat

Import the java.util.Date class to compare the two date objects

Once we have the date objects, it's a simple matter of using the class methods to do the comparisons. Oh, and by the way, make sure that you use the java.util.Date class and not the java.sql.Date class:

Android date comparison imports

The java.util.Date class creates dates which include hours, minutes, seconds and milliseconds. The java.sql.Date class does not. When a long value representing the date in milliseconds is passed to the java.sql.Date object, it normalises the date to the time 00:00:00:0000 GMT on the date represented by the millisecond value. When you use the Date class's after() and before() methods to compare the two dates, they work as expected however, the equals() method does not.

You could convert the two date objects into strings and then use the String's equal() method to compare the two strings, this renders the correct answer. I preferred to follow the route described above (using the java.util.Date class), confident that the date comparisons were performing as expected.