我正在尝试将以下两行代码从 C# 重写为 Java。
long ticks1970Onwards = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks;
long newTs = (DateTime.UtcNow.Ticks - ticks1970Onwards)/10000;
我尝试了多种方法,但没有得到正确的解决方案。
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
。
import java.time.Instant;
public class Main {
public static void main(String[] args) {
Instant now = Instant.now();
System.out.println(now.toEpochMilli());
}
}
您可以将此结果与 C# PlayGround 中的 C# 代码的结果进行比较。
注意: 避免使用 3 个字母缩写指定时区。应使用以下格式的名称指定时区,地区/城市,例如
ZoneId.of("Europe/London")
。根据此约定,可以使用 ZoneId
指定 UTC
的 ZoneId.of("Etc/UTC")
。以 UTC[+/-]Offset
指定的时区可以指定为 Etc/GMT[+/-]Offset
,例如ZoneId.of("Etc/GMT+1")
、ZoneId.of("Etc/GMT+1")
等
也有一些特殊情况,例如要指定
Turkey
的时区,您可以指定
ZoneId.of("Turkey")
但是,建议(感谢 Ole V.V.)使用与上述相同的模式,即表示土耳其时区的推荐方式是:
ZoneId.of("Asia/Istanbul")
或
ZoneId.of("Europe/Istanbul")
可能,
Istanbul
被两个地区/大陆引用是ZoneId.getAvailableZoneIds()
仍然返回它的原因。
以下代码将为您提供所有可用的
ZoneId
:
// Get the set of all time zone IDs.
Set<String> allZones = ZoneId.getAvailableZoneIds();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MILLISECOND, 0); // Clear the millis part. Silly API.
calendar.set(2010, 8, 14, 0, 0, 0); // Note that months are 0-based
Date date = calendar.getTime();
long millis = date.getTime(); // Millis since Unix epoch
导入java.util.*;
公开课测试{
private static final long TICKS_AT_EPOCH = 621355968000000000L;
private static final long TICKS_PER_MILLISECOND = 10000;
public static void main(String[] args) {
long ticks = 634200192000000000L;
Date date = new Date((ticks - TICKS_AT_EPOCH)/TICKS_PER_MILLISECOND);
System.out.println(date);
TimeZone utc = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(utc);
calendar.setTime(date);
System.out.println(calendar);
}
}
示例
导入java.util.Calendar; 导入 java.util.Date;
公共类 DateHelper {
private static final long TICKS_AT_EPOCH = 621355968000000000L;
private static final long TICKS_PER_MILLISECOND = 10000;
public static long getUTCTicks(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return (calendar.getTimeInMillis() * TICKS_PER_MILLISECOND) + TICKS_AT_EPOCH;
}
public static Date getDate(long UTCTicks){
return new Date((UTCTicks - TICKS_AT_EPOCH)/TICKS_PER_MILLISECOND);
}