LocalDateTime
has two fields of type LocalDate
and LocalTime
.
LocalDate
has fields day
, month
, and year
.
LocalTime
has fields hour
, minute
, second
, and nano
.
Nowhere in that is a time zone given. Which is by nature, since the javadoc of LocalDateTime
says:
A date-time without a time-zone
So, if the "local" date/time value is already representing a time in UTC, and you want it formatted saying so, you have multiple options:
Change the LocalDateTime
to a ZonedDateTime
by calling atZone()
:
System.out.println(time.atZone(ZoneOffset.UTC)
.format(DateTimeFormatter.ofPattern("hh:mm:ss a z")));
Specify an override time zone in the formatter by calling withZone()
:
System.out.println(time.format(DateTimeFormatter.ofPattern("hh:mm:ss a z")
.withZone(ZoneOffset.UTC)));
Format with a literal Z
character:
System.out.println(time.format(DateTimeFormatter.ofPattern("hh:mm:ss a 'Z'")));
All three of the above outputs:
11:59:22 PM Z
Now, if the "local" date/time is really in a different time zone, you can use either of the first two, and just specify the actual zone.
E.g. if time zone is -04:00
, use ZoneOffset.ofHours(-4)
, and you'll get:
11:59:22 PM -04:00
Or if you are in New York, use ZoneId.of("America/New_York")
, and you'll get:
11:59:22 PM EDT
If the "local" date/time is for New York, but you want formatted text to be UTC, use both at the same time, i.e.
System.out.println(time.atZone(ZoneId.of("America/New_York"))
.format(DateTimeFormatter.ofPattern("hh:mm:ss a z")
.withZone(ZoneOffset.UTC)));
With that, you get the time converted to:
03:59:22 AM Z
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…