Skip to content
Advertisement

Output RFC 3339 Timestamp in Java

I want to output a timestamp with a PST offset (e.g., 2008-11-13T13:23:30-08:00). java.util.SimpleDateFormat does not seem to output timezone offsets in the hour:minute format, it excludes the colon. Is there a simple way to get that timestamp in Java?

// I want 2008-11-13T12:23:30-08:00
String timestamp = new SimpleDateFormat("yyyy-MM-dd'T'h:m:ssZ").format(new Date());
System.out.println(timestamp); 
// prints "2008-11-13T12:23:30-0800" See the difference?

Also, SimpleDateFormat cannot properly parse the example above. It throws a ParseException.

// Throws a ParseException
new SimpleDateFormat("yyyy-MM-dd'T'h:m:ssZ").parse("2008-11-13T13:23:30-08:00")

Advertisement

Answer

Starting in Java 7, there’s the X pattern string for ISO8601 time zone. For strings in the format you describe, use XXX. See the documentation.

Sample:

System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX")
        .format(new Date()));

Result:

2014-03-31T14:11:29+02:00
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement