Reputation: 5495
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)
Upvotes: 4
Views: 8278
Reputation: 206796
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.
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).
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));
Upvotes: 12