views:

326

answers:

4

I'm trying to parse the time stamps written in some xml files. Most to the time time stamps are something like 2009-07-22-07:00 but some times I find them something like 2009-07-22Z or 2009-07-22z. Kindly help me how to interpret these Zs and how to parse them. I thing these z or Z is related to the time zone. Any workarounds to parse them just like the typical time stamps?

+5  A: 

The Z means Zulu. You're correct, it does represent the time zone - specifically UTC.

Greg
thank you so much for the quick answer
ram
+5  A: 

You're correct. The trailing character refers to the timezone.

The Z refers to the "Zulu" timezone, which is just shorthand for the UTC (or GMT) timezone.

You may also see a trailing +X or -X. These refer to the GMT offset for the timestamp. e.g. 2002-05-30+06:00 indicates that the time is GMT + 6 hours and zero minutes.

Glen
+1  A: 

XML uses ISO8601 time formats, so that standard is the first place to look for all things timerelated in XML.

fvu
A couple of nitpicks. 1) it is XML Schema that specifies dates based on ISO-8601 ... the base XML spec (and DOMs and parsers) does not have any notion of data types. 2) The time and duration types in XML Schema are only based on ISO-8601. If you read the XML Schema spec in detail you will see that there are subtle differences.
Stephen C
@Stephen - Indeed, you're right. http://www.w3.org/TR/xmlschema-2/#isoformats for an overview of these deviations.
fvu
+6  A: 

To add to fvu's answer: Java unfortunately does not have any built-in method to parse (or format ISO8601 date and time format, and even more unfortunately it is not (easily) possible to parse ISO8601 dates with java.text.SimpleDateFormat.

The well-known and popular Joda Time library does have good support for ISO8601 dates and times.

Edit: Since Java 5, there are classes in the standard API to parse and format dates and times in the standard format often used in XML documents. To parse a date:

import java.util.Calendar;
import java.util.Date;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

// ...

String dateString = "..."; // wherever you get this from
XMLGregorianCalendar xcal = DatatypeFactory.newInstance().newXMLGregorianCalendar(dateString);

Calendar cal = xcal.toGregorianCalendar();
Date date = cal.getTime();

Likewise there are methods to format dates into strings. See the API documentation of those classes for details.

Jesper
What he said. Just use Joda time, you'll thank the above poster in a few hours.
Gaurav
thanks for the detailed solution
ram
It says " non-static method newXMLGregorianCalendar(java.lang.String) cannot be referenced from a static context". Sorry I am a newbie to Java. What is the work around here?
ram
Small mistake, I'll edit the code in my answer...
Jesper