2

I have the following date:

2011-10-07T08:51:52.006Z

Now I want to parse it into a GregorianCalendar. Is there an easier way to do it than using substrings and parsing them to Integers?

And what is the Z in the time string?

I tried to parse it using SimpleDateFormat, but I can´t find a explanation for the T in the date String.

3 Answers 3

7
DateFormat format = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" )
Date       date = format.parse( "2011-10-07T08:51:52.006Z" );
Calendar   calendar = new GregorianCalendar();

calendar.setTime( date );
2
  • The Z (as noted in Gonzalo's answer) is not a constant letter ('Z') but rather an abbreviation for GMT time when using the XXXX ISO-8601 format.
    – johnstosh
    Oct 20, 2015 at 18:14
  • Calling calendar.setTime( date ) will set the time in millis, but looses the timezone information (the XXXX format as shown by the Z in the example.)
    – johnstosh
    Oct 20, 2015 at 18:16
2

I would take a look at DateTimeFormatter

DateTimeFormatter formatter =
    DateTimeFormat.forPattern("<custom_pattern>").withOffsetParsed();
DateTime dateTime = formatter.parseDateTime("<your_input>");
GregorianCalendar cal = dateTime.toGregorianCalendar();

The T in your string acts as a separator between the date and the time and the Z is the time-zone information both as per ISO-8601 format.

1

You could use the SimpleDateFormatter to parse the String. Please read the javadoc for the aforementioned class to know what could be the format string. 'Z' indicates the timezone information.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.