Dan James
Dan James

Reputation: 83

How to change timezone in ZonedDateTime for Java

What I mean is this. Suppose I have a date object that is May 1, 2018, 12:00AM. I would like to create a ZonedDateTime object that is May 1, 2018, 12:00AM but of ANOTHER time zone (say EST). Because if I pass in that date object into ZonedDateTime, it treats that date object as UTC (so it treats it as May 1 2018, 12:00AM GMT), and I want it to preserve that date field values but change the timzeone to EST (May 1st 2018, 12:00AM EST). Is there a way to do this in Java?

Upvotes: 8

Views: 15180

Answers (1)

Anonymous
Anonymous

Reputation: 86296

What you need is a LocalDate:

    LocalDate date = LocalDate.of(2018, Month.MAY, 1);

This will be understood in all time zones and will never be anything else than May 1. The “Local” in this and other class names in java.time means “without timezone”.

If you do insist on a ZonedDateTime, the answer is withZoneSameLocal:

    ZonedDateTime zdt = date.atStartOfDay(ZoneOffset.UTC);
    ZonedDateTime inEst = zdt.withZoneSameLocal(ZoneId.of("Australia/Brisbane"));
    System.out.println(inEst);

Output:

2018-05-01T00:00+10:00[Australia/Brisbane]

Don’t rely on EST or other three and four letter time zone abbreviations. EST, for example, is ambiguous (used both in North America and Australia) and is not a time zone (used less than half of the year). Instead give region/city, for example America/Atikokan.

If by “a date object” you meant an object of the outdated java.util.Date class (avoid them if you can, prefer the modern classes in java.time):

    Date oldfashionedDate = // …;

    OffsetDateTime dateTime = oldfashionedDate.toInstant().atOffset(ZoneOffset.UTC);
    if (! dateTime.toLocalTime().equals(LocalTime.MIDNIGHT)) {
        throw new IllegalStateException("java.util.Date was supposed to be at midnight in UTC but was " + dateTime);
    }
    LocalDate date = dateTime.toLocalDate();
    System.out.println(date);

Output:

2018-05-01

Upvotes: 11

Related Questions