Reputation: 4785
Is there an easy way to achieve System.currentTimeMillis()
to 2017-04-13T19:00:00+08:00
using java.time
?
I have tried tremendous amount of methods so far, but it either gives the correct zone but in a wrong language, or does not give any zone at all.
Instant shanghai= Instant.ofEpochMilli(System.currentTimeMillis());
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL)
.withZone(ZoneId.of("Asia/Shanghai"));
System.out.println(formatter.format(shanghai));
BTW, maybe it's because I haven't used Java 8 time API enough times to see its beauty, but I do feel it as "drawing snake with feet".
For example, withZone
sounds like it shifts time result to accommodate zone. But it actually change the language too, which I think should only be related to Locale
.
Upvotes: 1
Views: 2410
Reputation: 298153
The long
returned by methods like System.currentTimeMillis()
representing the milliseconds since the epoch describes an Instant
(instantaneous point) on the time line and can be converted to an object representation using Instant.ofEpochMilli(…)
long l = System.currentTimeMillis();
System.out.println(Instant.ofEpochMilli(l));
2017-09-19T08:17:37.054Z
To convert it to a datetime with offset, you can use OffsetDateTime.ofInstant(…)
:
System.out.println(
OffsetDateTime.ofInstant(Instant.ofEpochMilli(l), ZoneId.of("Asia/Shanghai")));
2017-09-19T16:17:37.054+08:00
Note that a formatter is not necessary here.
Upvotes: 3
Reputation: 15684
I'm going to suggest by-passing System.currentTimeMillis()
and jump straight into the land of java.time
:
System.out.println(OffsetDateTime.now());
For me prints: 2017-09-19T06:07:12.814+01:00
Upvotes: 3
Reputation: 4785
I finally got the ISO8601 time!
Instant shanghai = Instant.ofEpochMilli(System.currentTimeMillis());
OffsetDateTime o = OffsetDateTime.ofInstant(shanghai,ZoneId.systemDefault());
DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
System.out.println(dtf.format(o));
After DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(Instant.now())
complains something wrong with the offset, and after DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(...)
complains about the year...
Upvotes: 1