0

There can be two different date time formats as shown below. The second variant has milliseconds time.

2020-09-07T16:15:42Z
2020-09-09T11:41:58.5152Z

Currently i am using this way to parse the date. Is there a way to specify a single format to account for both of these two cases?

def dateutc = (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'"))

 dateutc.setTimeZone(TimeZone.getTimeZone("UTC"))

 time = dateutc.parse(point.time.toString()).getTime()

Thanks for the help!

Please note i am using java 7.

kofhearts
  • 3,607
  • 8
  • 46
  • 79
  • 1
    A "common" approach is to use multiple (strict) formats and continue trying to parse the input until you get a result – MadProgrammer Sep 12 '20 at 05:42
  • do you mean catching the exception if it doesnt work and applying another format and trying that if that throws exception? – kofhearts Sep 12 '20 at 05:52
  • Yes, essentially – MadProgrammer Sep 12 '20 at 05:53
  • thanks ill try that. could there be a better way? – kofhearts Sep 12 '20 at 05:55
  • Not that I've found - at least which would be reliable – MadProgrammer Sep 12 '20 at 06:00
  • @kofhearts Update to Java 8 and use `java.time`. ;-) – akuzminykh Sep 12 '20 at 06:00
  • 4
    Does this answer your question? [How to parse dates in multiple formats using SimpleDateFormat](https://stackoverflow.com/questions/4024544/how-to-parse-dates-in-multiple-formats-using-simpledateformat) – akuzminykh Sep 12 '20 at 06:01
  • thanks. that link also suggests the same approach as MadProgrammer. I went with MadProgrammer's suggestion. thanks! – kofhearts Sep 13 '20 at 04:29
  • You can’t with `SimpleDateFormat`. There is no way that it can parse four decimals on the seoncds. Also I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead just use `Instant` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Sep 14 '20 at 05:56
  • 1
    If using Java 8 is somehow not an option, then get the ThreeTen Backport, which backports the Java 8 Date and Time API to Java 6 and 7. – MC Emperor Sep 14 '20 at 06:03
  • @MCEmperor I was just going to say that. [Link: ThreeTen Backport](https://www.threeten.org/threetenbp/apidocs/index.html). With ThreeTen Backport on Java 7 `Instant.parse("2020-09-07T16:15:42Z").toEpochMilli()` yields `1599495342000`. With `2020-09-09T11:41:58.5152Z` instead the result is `1599651718515`. – Ole V.V. Sep 14 '20 at 06:06

0 Answers0