本文介绍了如何在Java中从C#编写DateTime.UtcNow.Ticks的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将下面两行代码从C#重写为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);

推荐答案

Instant#toEpochMilli

使用它来转换 Instant.now() 到从1970-01-01T00:00:00Z的纪元开始的毫秒数,其中Z代表Zulu时间并代表UTC.

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

您可以将此结果与C#代码的结果进行比较,网址为 C#PlayGround .

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

注意:避免使用3个字母的缩写指定时区.时区的名称应采用 Region/City (地区/城市)格式,例如ZoneId.of("Europe/London").按照此约定,可以用ZoneId.of("Etc/UTC")指定UTCZoneId.可以将以UTC[+/-]Offset表示的时区指定为Etc/GMT[+/-]Offset,例如ZoneId.of("Etc/GMT+1")ZoneId.of("Etc/GMT+1")

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.

还有一些例外情况,例如要指定Turkey的时区,您可以指定

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")

ZoneId.of("Europe/Istanbul")

Istanbul可能有两个区域/大陆被引用,这是ZoneId.getAvailableZoneIds()仍返回它的原因.

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

以下代码将为您提供所有可用的ZoneId:

The following code will give you all the available ZoneIds:

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

这篇关于如何在Java中从C#编写DateTime.UtcNow.Ticks的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 18:47