I have date objects formatted like
2011/06/13 17:52:20
and being returned as strings. How would I compare this against another date formatted the same way. I want to determine which one is greater than, less than or equal to, for a conditional statement I am forming.
Without reinventing the wheel (or making several cases) when there might already be a framework for doing this
Thanks!
Although SimpleDateFormat allows one to parse text into a date object, you're much better off storing the date as a Date object and parsing it on display.
Create/Store Date objects and use their built-in compareTo() method.
tl;dr
Details
The other Answers are correct in that you can either (a) alphabetically compare those particular strings, or (b) chronologically compare after parsing into date-time objects.
And be aware that date-time formats do not have a “format”. They contain date-time information. They can generate a String that is in a particular format, but the date-time object and the string are separate and distinct.
The other Answers use the troublesome old date-time classes that are now legacy, supplanted with the java.time classes.
Your inputs lack info about offset-from-UTC and time zone. So we must parse them as
LocalDateTime
objects. To parse, replace the SPACE in the middle with aT
to comply with the ISO 8601 standard for formatting strings that represent date-time values.Compare.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as
java.util.Date
,Calendar
, &SimpleDateFormat
.The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as
Interval
,YearWeek
,YearQuarter
, and more.My colleagues pointed out to me last week that yyyy-MM-dd HH:mm:ss strings is completely compatible with the ordering of the underlying dates (as long as the fields are all zero padded). So you can just to the compareTo on the String values if they are more readily available.
It looks to me like your date format is yyyy/mm/dd hh:mm:ss. If that's the case, you can do a string compare and it will give you an accurate greater/less/equal. The string is coded as most signficant to least significant.
SimpleDateFormat
to parsecompareTo(..)
of theDate
objects that are obtainedFor example:
The result is (from the
java.util.Date
documentation):