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:

JavaScript

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

JavaScript

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:

JavaScript

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:

JavaScript

On my system, this outputs

JavaScript

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