If you want to be able to write code that reflects the difference between offsets and time zones, leave java.util
and switch to java.time
(for Java 8+ and with a support library for Java 6 and 7).
Then you can do things like these:
public static void main(String[] args) {
/*
* the base of this example is a date time with an offset of +01:00
* (which is present in several zones, not just in Europe/Amsterdam!)
*/
String datetime = "2019-11-28T12:49:24.000+01:00";
// parse it to an offset-aware object
OffsetDateTime plusOneHourOffsetDateTime = OffsetDateTime.parse(datetime);
// print it to be sure ;-)
System.out.println(plusOneHourOffsetDateTime
.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
// convert it to a zone-aware date time object by providing the zone
ZonedDateTime europeAmsterdamZonedDateTime = plusOneHourOffsetDateTime
.atZoneSameInstant(ZoneId.of("Europe/Amsterdam"));
// print it
System.out.println(europeAmsterdamZonedDateTime
.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
// then take the same instant but use a different time zone
ZonedDateTime utcZonedDateTime = plusOneHourOffsetDateTime
.atZoneSameInstant(ZoneId.of("UTC"));
// print that, it adds a Z (indicating an offset of 00:00) and the time zone
// that was specified
System.out.println(utcZonedDateTime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
// take a totally different time zone and do it again
ZonedDateTime pacificPalauZonedDateTime = plusOneHourOffsetDateTime
.atZoneSameInstant(ZoneId.of("Pacific/Palau"));
// print that one, too
System.out.println(pacificPalauZonedDateTime
.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
}
which outputs this
2019-11-28T12:49:24+01:00
2019-11-28T12:49:24+01:00[Europe/Amsterdam]
2019-11-28T11:49:24Z[UTC]
2019-11-28T20:49:24+09:00[Pacific/Palau]
EDIT
The reason for the DateTimeParseException
mentioned in your comment is the date-time String
, because it doesn't have a zone or an offset, which makes it unparseable by the default DateTimeFormatter
used in OffsetDateTime.parse(String datetime)
.
If you have a String
with date and time information but without a zone or an offset, you can parse it to a LocalDateTime
first and create a ZonedDateTime
from that:
public static void main(String[] args) {
// date time String without zone or offset information
String dateTimeString = "2019-11-30T19:35:06";
// create a LocalDateTime from the String
LocalDateTime ldt = LocalDateTime.parse(dateTimeString);
// then create a ZonedDateTime from the LocalDateTime adding a zone
ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault()); // system default here
// and print it
System.out.println(zdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
}