Question

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?

Était-ce utile?

La solution

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.

Autres conseils

No, the better approach would be parse the string in a date object and then compare with other date object.

I wouldn't worry about performance unless you have some reason to think this code will be a bottleneck (called lots of times within loops) and even then I'd wait till you could do some concrete performance testing.

Comparing them as dates will make your code clearer and will mean you can more easily change the date format in future (to something which doesn't sort as a string).

It works provided

  • You order the fields from most significant to least significant.
  • You use number fields (not Jan/Feb) and they are the same width. e.g. 2:15 is after 12:15 but 02:15 is before as expected. Note: For years after 9999 and before 0001 this will not work.
  • You accept that invalid dates may not be detected.

Use the type that it represents - in this case it's a date so use a date. Dates can easily be sorted chronologically by adding them to a collection and doing Collections.sort(dates) on the dates.

See http://docs.oracle.com/javase/tutorial/collections/interfaces/order.html

I think Date is compared or can be compared through miliseconds (long) which is faster. It's probably safer way, you don't need to think about when string comparation would not fit.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top