Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
577 views
in Technique[技术] by (71.8m points)

How can I write DateTime.UtcNow.Ticks from C# in java

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

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

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...