0

Trying to parse the following timestamp:

2008-09-19T19:05:30.000Z

However I am getting a parseException. Is anyone aware of a class or SimpleDateFormat that could take care of this?

What I am using now in Scala (Java answers work, too):

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

Thanks for your help.

crockpotveggies
  • 12,682
  • 12
  • 70
  • 140

3 Answers3

3

And single quotes (') around the Z. This instructs the parser to treat Z as a constant character (just like the T). Also add in SSS for the milliseconds. Thus your pattern would be yyyy-MM-dd'T'HH:mm:ss.SSS'Z'

Steve Kuo
  • 61,876
  • 75
  • 195
  • 257
  • I can confirm this also worked, and switching it to the answer on the reason that it accounts for ms – crockpotveggies Aug 30 '12 at 01:09
  • @DeLongey (Which you can't get in a trivial way from a `Date`.) If you must match the pattern *exactly*, you must *also* `setLenient(false)` or it will match inexact patterns. – Dave Newton Aug 30 '12 at 01:11
0

This piece of code from Google client libraries did the trick:

http://javadoc.google-api-java-client.googlecode.com/hg/1.0.10-alpha/com/google/api/client/util/DateTime.html

Use the parseRFC3339 method.

crockpotveggies
  • 12,682
  • 12
  • 70
  • 140
0

Remove the Z:

> sdf = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
> println sdf.parse("2008-09-19T19:05:30.000Z")
Fri Sep 19 19:05:30 EDT 2008
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • 1
    This is a suboptimal answer in that it relies on SimpleDateFormat not matching anything after the format string. See http://stackoverflow.com/questions/8428313/simpledateformat-parsestring-str-didnt-been-throw-when-str-2011-12-12aaaaaa – Steve Kuo Aug 30 '12 at 00:56
  • @SteveKuo Agreed, if OP actually *needs* the ms... which is a pain with a `Date` anyway. Of course, you'd also need to `setLenient(false)`, otherwise non-exact patterns may still match. – Dave Newton Aug 30 '12 at 01:10