Producing W3C Datetime Format with Timezone in Java


W3C Datetime (also known as ISO 8601) is a standard machine readable way of formatting dates. In its most specific form, dates can be printed with time and time zone in this format:

YYYY-MM-DDThh:mm:ss.sTZD

For example:

1997-07-16T19:20:30.45+01:00

It is not as easy to produce dates in this format in Java as it should be. I needed to format dates like this for creating an XML Sitemap file.

The go to class for printing dates is SimpleDateFormat. Simple date format can almost do it:

new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US)

The problem is that this simple date format omits the colon in the time zone, so the date comes out like:

1997-07-16T19:20:30.45+0100

One approach is to insert the missing colon into the date:

DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US);
String date = format.format(new Date()).replaceAll("(.*)(\\d\\d)$", "$1:$2");

A solution that I like better is to print the date in GMT without the timezone and append a zero timezone:

DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
String date = format.format(new Date())+"+00:00";

Leave a comment

Your email address will not be published. Required fields are marked *