Using SimpleDateFormat on Java 7 or newer
Use XXX
for the timezone in the format string instead of Z
:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmXXX");
This works if you are using Java 7 or newer.
Java version 6 or older
For older versions of Java, you can use the class javax.xml.bind.DatatypeConverter
:
import javax.xml.bind.DatatypeConverter;
// ...
Calendar cal = Calendar.getInstance();
cal.setTime(new java.util.Date(timeInLong));
System.out.println(DatatypeConverter.printDateTime(cal));
Note that this will add milliseconds, so the output will be for example 2014-11-04T15:49:35.913+01:00
instead of 2014-11-04T15:49:35+01:00
(but that shouldn't matter, as this is still valid ISO-8601 format).
Java version 8 or newer
If you are using Java 8, then it's preferrable to use the new java.time
API instead of java.util.Date
:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
ZonedDateTime zdt = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timeInLong),
ZoneId.systemDefault());
System.out.println(zdt.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));