Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to rewrite below two lines of code from C# into Java.

long ticks1970Onwards = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks;
 long newTs =    (DateTime.UtcNow.Ticks - ticks1970Onwards)/10000;

I tried multiple ways , but I don't get the correct solution.

        ZonedDateTime dt1 = LocalDateTime.now().atZone(ZoneId.of("UTC"));
        ZonedDateTime dt2 = LocalDateTime.of(1901, 1, 1, 0, 0).atZone(ZoneId.of("UTC"));
        Duration duration2 = Duration.between(dt2, dt1);
        System.out.printf("Duration = %s milliseconds.%n", duration2.getSeconds()*1000);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
571 views
Welcome To Ask or Share your Answers For Others

1 Answer

Instant#toEpochMilli

Use it to convert Instant.now() to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z where Z stands for Zulu time and represents UTC.

import java.time.Instant;

public class Main {
    public static void main(String[] args) {
        Instant now = Instant.now();
        System.out.println(now.toEpochMilli());
    }
}

You can compare this result with that of the C# code at C# PlayGround.

Note: Avoid specifying a timezone with the 3-letter abbreviation. A timezone should be specified with a name in the format, Region/City e.g. ZoneId.of("Europe/London"). With this convention, the ZoneId for UTC can be specified with ZoneId.of("Etc/UTC"). A timezone specified in terms of UTC[+/-]Offset can be specified as Etc/GMT[+/-]Offset e.g. ZoneId.of("Etc/GMT+1"), ZoneId.of("Etc/GMT+1") etc.

There are some exceptional cases as well e.g. to specify the timezone of Turkey, you can specify

ZoneId.of("Turkey")

However, it is recommended (Thanks to Ole V.V.) to use the same pattern as described above i.e. the recommended way of representing the timezone of Turkey is:

ZoneId.of("Asia/Istanbul")

or

ZoneId.of("Europe/Istanbul")

Probably, Istanbul being referred with two regions/continents is the reason why it is still returned by ZoneId.getAvailableZoneIds().

The following code will give you all the available ZoneIds:

// Get the set of all time zone IDs.
Set<String> allZones = ZoneId.getAvailableZoneIds();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...