From an external service I get objects with Date+Time
fields as String
's in format 2012-03-07 12:12:23.547
and I need to compare these fields to get a correct order of the objects. I am well aware that I can create Date
objects via e.g. SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") and compare the two Date
's to achieve this but my question is if I can rely on a correct sorting order if I compare them as Strings such as String.compareTo(String)
? Some light testing gives me the impression that it works but I am wondering if anyone is aware of any scenarios where it would NOT give me the correct result? Also, are there any performance considerations, pros or cons, of comparing String
's Vs parsing into Dates to compare?
Assuming the hours are in 24 hour format, then yes, that's a sortable date/time format - and one of its well-known benefits is that you can sort without actually parsing.
One downside: if you get bad data, you won't spot it - you'll just neatly sort it into the "right" place, ignoring the fact that you've been given (say) February 30th.
If you need the value as a date/time later on, then I'd parse it first and then compare. But if you only need this in terms of ordering, the string comparison may be faster than parsing everything. Worth benchmarking, of course... especially as comparing two strings on the same day will require several characters-worth of checking, whereas if you've parsed it once you can then probably just compare long
values.