You can parse your String
to a LocalDateTime
(only date and time of day, NO zone and NO offset from UTC / GMT).
If you apply a specific zone afterwards, you can build a ZonedDateTime
, which can be formatted as desired.
A ZonedDateTime
can be converted to an Instant
, and that is an option for legacy compatibility, because there are Date.from(Instant)
and Date.toInstant()
.
Here's an example with different outputs
public static void main(String[] args) {
// example input
String value = "20230607121201";
// create a formatter for parsing the String
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMMddHHmmss");
// parse the String to a
LocalDateTime localDateTime = LocalDateTime.parse(value, dtf);
// create the desired zone id
ZoneId zoneId = ZoneId.of("Europe/Kaliningrad");
// compose the LocalDateTime and the ZoneId
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
// create a formatter with the same format as Date.toString()
DateTimeFormatter dtfOut = DateTimeFormatter.ofPattern(
"EEE MMM dd HH:mm:ss z uuuu",
Locale.ENGLISH);
// get the Instant
Instant instant = zonedDateTime.toInstant();
// create a Date from the Instant
Date date = Date.from(instant);
// print the different representations
System.out.println("ZonedDateTime.format(): " + zonedDateTime.format(dtfOut));
System.out.println("Instant.toEpochMilli(): " + instant.toEpochMilli());
System.out.println("Date.getTime(): " + date.getTime());
System.out.println("Date.toString(): " + date);
}
Please note that Date.toString()
takes the system locale and time zone into account, obviously not knowing about daylight saving time.
This took my Locale
…
Output
ZonedDateTime.format(): Wed Jun 07 12:12:01 EET 2023
Instant.toEpochMilli(): 1686132721000
Date.getTime(): 1686132721000
Date.toString(): Wed Jun 07 12:12:01 CEST 2023
Please note that both, Instant.toEpochMilli()
and Date.getTime()
, have the same value of epoch millis!
Why ZoneId.of("Europe/Kaliningrad")
?
Because the requirement seems to be to always use EET. That means you have to choose a zone id that
- is in / uses EET
- does not apply daylight saving time