The existing answers are correct but have missed some crucial information.
- While
Z
represents the time-zone offset only, V
represents the time-zone ID which gives a ZonedDateTime
its identity. Learn more about it from DateTimeFormatter
documentation. While a time-zone ID of a place is fixed, the time-zone offset varies if the place observes DST (e.g. Europe/London has +01:00 offset in summer and +00:00, also represented as Z
, offset in winter).
- One should always use
Locale
while using date-time parsing/formatting API because they are Locale
-sensitive. Check Never use Date-Time formatting/parsing API without a Locale to learn more about it.
- Since
LocalDateTime
does not contain any information about time-zone, it should be formatted without any letter that represents time-zone related information. It is obvious that a formatter for LocalDateTime
can always be used to format a ZonedDateTime
but the reverse may fail (if it contains time-zone related character). If required, a ZonedDateTime
representing the system's time zone can be derived from a LocalDateTime
.
- I also prefer u to y with
DateTimeFormatter
.
Demo:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter ldtFormatter = DateTimeFormatter.ofPattern("uuuuMMdd HH:mm:ss.SSSSSS", Locale.ENGLISH);
System.out.println(LocalDateTime.now().format(ldtFormatter));
// ZZZZZ can be replaced with XXX
DateTimeFormatter zdtFormatter = DateTimeFormatter.ofPattern("uuuuMMdd HH:mm:ss.SSSSSS VV ZZZZZ",
Locale.ENGLISH);
System.out.println(ZonedDateTime.now().format(zdtFormatter));
System.out.println(ZonedDateTime.now().getZone());
// Deriving ZonedDateTime from LocalDateTime using system's time zone
LocalDateTime ldt = LocalDateTime.of(LocalDate.of(2022, 12, 15), LocalTime.of(10, 20, 30));
ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
System.out.println(zdt.format(zdtFormatter));
}
}
Output:
20221013 20:55:13.466830
20221013 20:55:13.468847 Europe/London +01:00
Europe/London
20221215 10:20:30.000000 Europe/London Z
Learn more about the the modern date-time API from Trail: Date Time.