Java Offset DateTime Formatter

Java Offset DateTime Formatter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public final class Bootstrap {
public static void main(String[] argv) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Instant now = Instant.now();
List<OffsetDateTime> dts = new ArrayList<>(3);

OffsetDateTime current = OffsetDateTime.ofInstant(now, ZoneId.systemDefault());
dts.add(current);

current = OffsetDateTime.ofInstant(now, ZoneId.ofOffset("UTC", ZoneOffset.ofHours(5)));
dts.add(current);

current = OffsetDateTime.ofInstant(now, ZoneId.ofOffset("UTC", ZoneOffset.ofHours(0)));
dts.add(current);

for (OffsetDateTime dt : dts) {
String str = formatter.format(dt);
System.out.println(str);
}
}
}
1
2
3
2020-01-11T13:05:21.621+0800
2020-01-11T10:05:21.621+0500
2020-01-11T05:05:21.621+0000