如何将.NET DateTime.toBinary()转换为Java日期 [英] How to convert .NET DateTime.toBinary() to java date
问题描述
我有一个来自JSON响应的.NET INT64值(从DateTime.toBinary()返回)为-8586018589234214115.如何将该值转换为有效的Java日期?
I have a .NET INT64 value(result from DateTime.toBinary()) as -8586018589234214115 from JSON response. How do I convert that value into valid java Date?
谢谢,桑迪普
推荐答案
一个64位带符号整数,该整数编码 A 64-bit signed integer that encodes the 由于 Since the A 勾号是: A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 此属性的值表示自 The value of this property represents the number of 100-nanosecond intervals that have elapsed since 这意味着我们可以这样转换: Which means we can convert like this: 测试 输出 警告: Warning: The 我们还可以采用其他方式进行转换: We can also convert the other way: 测试 输出 另请参见: Java 8时间-等效于.NET DateTime.MaxValue.Ticks 这篇关于如何将.NET DateTime.toBinary()转换为Java日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!种类
属性(位于2位字段中)和
Kind
property in a 2-bit field and the Ticks
property in a 62-bit field. Kind
属性对我们没有用,因此我们可以简单地使用 value&(((1L<<<< 62)-1)
来获取 Ticks
属性.Kind
property is useless to us, we can simply mask it out using value & ((1L << 62) - 1)
to get the Ticks
property.
10,000
ticks in a millisecond (see TicksPerMillisecond
) and 10 million ticks in a second. 0001年1月1日午夜12:00:00以来已经过去的100纳秒间隔的数量.
12:00:00 midnight, January 1, 0001
.private static final long NANOS_PER_TICK = 100L;
private static final long TICKS_PER_SECOND = 1000000000L / NANOS_PER_TICK;
private static final long YEAR_OFFSET = -62135596800L;
// Seconds from Epoch to 12:00:00 midnight, January 1, 0001, calculated using:
// OffsetDateTime.of(1, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC).toEpochSecond()
static Instant fromDateTimeBinary(long value) {
long ticks = value & ((1L << 62) - 1);
return Instant.ofEpochSecond(ticks / TICKS_PER_SECOND + YEAR_OFFSET,
ticks % TICKS_PER_SECOND * NANOS_PER_TICK);
}
long dateTimeBinary = -8586018589234214115L;
System.out.println(dateTimeBinary + " -> " + fromDateTimeBinary(dateTimeBinary));
-8586018589234214115 -> 2020-09-10T14:26:02.056169300Z
-8586018589234214115
值指定 Kind
值为 2 = Local
(表示的时间是当地时间),但我们不知道本地"时间是什么时区,因此转换为UTC的结果可能是错误的.-8586018589234214115
value specifies a Kind
value of 2=Local
(the time represented is local time), but we don't know what the "local" time zone was, so the result of converting to UTC may be wrong.static long toDateTimeBinary(Instant dateTime) {
long ticks = (dateTime.getEpochSecond() - YEAR_OFFSET) * TICKS_PER_SECOND
+ dateTime.getNano() / NANOS_PER_TICK;
return (0x01L/*Kind=UTC*/ << 62) | ticks;
}
Instant now = Instant.now();
System.out.println(now + " -> " + toDateTimeBinary(now));
2020-12-16T01:51:17.066065200Z -> 5249122821198048556