简体   繁体   中英

Java - long time to ISO_8601 string format

I want to convert a date in long to a ISO_8601 string.

ex:

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 in my console

2014-11-04T15:57+0200

I think that I want to get it

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

How can I do that? (without string functions)

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM