Java - long time in ISO_8601 string format

I want to convert a date long to a string ISO_8601

.

Example:

2014-11-02T20:22:35.059823+01:00

      

My code

long timeInLong=System.currentTimeMillis();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
String fmm = df.format(new java.util.Date(timeInLong));
System.out.println(fmm);

      

This will show up on my console

2014-11-04T15:57+0200

      

I think I want to get it

2014-11-04T15:57+02:00

      

How can i do this? (no string functions)

+3


source to share


1 answer


Using SimpleDateFormat in Java 7 or later

Use XXX

for the timezone in the format string instead 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 later

For older Java versions, 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 look like, for example, 2014-11-04T15:49:35.913+01:00

and not 2014-11-04T15:49:35+01:00

(but that doesn't matter since this is still valid ISO-8601 format).

Java version 8 or newer

If you are using Java 8 then it prefers 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));

      

+7


source







All Articles