1

I receive timestamps in the form of Strings. I want to sort these timestamps. If the format of the timestamps is "yyyy-MM-dd HH:mm:ss.SSS", do I just compare them as Strings using compareTo function? This will solve the purpose, but is that a good practice?

tjc371
  • 43
  • 6
  • Would timezones be a problem? – Thorbjørn Ravn Andersen Jul 04 '15 at 09:14
  • No... What if the timestamps have different timezones... You compareTo method will give wrong results... – Codebender Jul 04 '15 at 09:14
  • @Codebender: That format doesn't specify a time zone at all - so if they can be local representations from multiple time zones then there's a bigger problem... – Jon Skeet Jul 04 '15 at 09:15
  • 1
    http://stackoverflow.com/questions/25963720/how-to-compare-two-string-dates-in-java – Rodolfo Jul 04 '15 at 09:16
  • @Codebender @ Thorbjørn Ravn Andersen: No, timezone is not a problem. It's a given that all timestamps have the same timezone. – tjc371 Jul 04 '15 at 09:18
  • 1
    http://stackoverflow.com/questions/5301226/convert-string-to-calendar-object-in-java – Rodolfo Jul 04 '15 at 09:18
  • Actually it depends what the timestamps represent. If they are supposed to represent an event that happens at world time, i.e. these happened in these countries at this time around the world then yes tz should be considered. However if they represent a timestamp relative to the time of day in any given zone, i.e. events happen at this time of day in these countries then no tz is not required and would srcew the comparison up. – Tuxxy_Thang Jul 04 '15 at 09:24
  • 2
    Clearly, the string comparison will work in your case. Whether it's a good practice is a matter of opinion (and therefore not a good Stack Overflow question). But if you decide to do it, make sure you document your assumptions in the code. That is, state clearly what the format is, and that everything is in the same timezone. – Dawood ibn Kareem Jul 04 '15 at 09:25
  • This might help : http://stackoverflow.com/questions/8769456/comparing-two-timestamps – Arpit Aggarwal Jul 04 '15 at 10:14

1 Answers1

0

The correct way to compare timestamps is to compare them as Date objects:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
boolean firstBeforeSecond = sdf.parse(firstDate).before(sdf.parse(secondDate));
Nico Weisenauer
  • 284
  • 1
  • 7