Convert time in long format from UTC to EST

83 views Asked by At

Looking for ideas to convert time in long (millis) from UTC to EST Tried in the below manner and did not work. I am seeing epcohET is same as input parameter.

long time = 1693932120000
Instant dateTime = Instant.ofEpochMilli(time);
ZoneId usET = ServerTimeZone.TimeZone.getTimeZone("America/New_York").toZoneId();
ZonedDateTime zdt = ZonedDateTime.ofInstant(dateTime, usET);
long epochET = zdt.toInstant().toEpochMilli();
2

There are 2 answers

2
Arvind Kumar Avinash On

Instant represents just a moment in time and is independent of the timezone.

You can use Instant#atZone to get the desired result.

Demo:

class Main {
    public static void main(String[] args) {
        long timestamp = 1693932120000L;
        Instant instant = Instant.ofEpochMilli(timestamp);
        ZonedDateTime zdt = instant.atZone(ZoneId.of("America/New_York"));
        System.out.println(zdt);
    }
}

Output:

2023-09-05T12:42-04:00[America/New_York]

Online Demo

Learn about the modern date-time API from Trail: Date Time

0
WJS On

So is there any other way to get convert long time from UTC to ET (without using ZonedDateTime)?

If you're talking about long from one TZ to long in another, no. Instants and epochs don't have time zones (although Instant is treated as Zulu for adjustment purposes).

If you just want to get a time object and don't care about timezone information and just want long milli adjusted for some timezone in a LocalDateTime this will work. If you want timezones to be included in the output, simply replace the calls using LocalDateTime with ZonedDateTime Try it like this but use your specific Zones. Note that if you print out an Instant it defaults to Zulu or UTC. So any TZ adjustment will be made from that point.

Long millis = 1694009579442L;
Instant instant = Instant.ofEpochMilli(millis);


LocalDateTime ldt1 = LocalDateTime.ofInstant(instant,
        ZoneId.of("US/Eastern"));
LocalDateTime ldt2 = LocalDateTime.ofInstant(instant,
        ZoneId.of("Europe/Paris"));
System.out.println(ldt1);
System.out.println(ldt2);

prints

2023-09-06T10:12:59.442
2023-09-06T16:12:59.442