Skip to content
Advertisement

Can’t get local and utc Instant

I need to get local time and utc time in seconds. I read some posts in StackOverflow and found some solution, which is correct as mentioned:

    Instant time = Instant.now();
    OffsetDateTime utc = time.atOffset(ZoneOffset.UTC);
    int utcTime = (int) utc.toEpochSecond();
    int localTime = (int) time.getEpochSecond();
    System.out.println("utc " + utcTime + " local " + localTime);

But result is not what I expected. It is utc time. The output:

utc   1593762925
local 1593762925

After debugging I found that Instant.now() is already utc. I can’t find how to get time in current time zone, i.e. my system zone.

I found some solution in API but got error:

OffsetDateTime utc = time.atOffset(ZoneOffset.of(ZoneOffset.systemDefault().getId()));

Exception in thread “main” java.time.DateTimeException: Invalid ID for ZoneOffset, invalid format: Europe/Astrakhan at java.base/java.time.ZoneOffset.of(ZoneOffset.java:241)

UPD: My question is How to get current time in seconds in local time zone and in UTC? I.e. the number of seconds since 1970-01-01T00:00:00 GMT+4 and 1970-01-01T00:00:00 GMT+0

UPD2: I have some device that needs response with utc time in seconds from 1970 and sender local time in seconds. Why? I don’t know. It is black box for me.

Advertisement

Answer

I think you need to take the Instant, create a ZonedDateTime (OffsetDateTime may be suitable as well) by applying a ZoneId.of("UTC") and then take that ZonedDateTime and use it to shift the locale:

public static void main(String[] args) {
    Instant now = Instant.now();
    
    ZonedDateTime utcZdt = now.atZone(ZoneId.of("UTC"));
    ZonedDateTime localZdt = utcZdt.withZoneSameLocal(ZoneId.systemDefault());
    
    System.out.println(utcZdt.toEpochSecond() + " <== " + utcZdt);
    System.out.println(localZdt.toEpochSecond() + " <== " + localZdt);
}

On my system, this outputs

1593765852 <== 2020-07-03T08:44:12.070Z[UTC]
1593758652 <== 2020-07-03T08:44:12.070+02:00[Europe/Berlin]

Two hours difference are affecting the sixth digit of the epoch seconds.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement