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:


For example:


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:


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);
String date = format.format(new Date())+"+00:00";

Leave a comment

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