如何将.NET DateTime.toBinary()转换为Java日期 [英] How to convert .NET DateTime.toBinary() to java date

查看:96
本文介绍了如何将.NET DateTime.toBinary()转换为Java日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自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位带符号整数,该整数编码 种类 属性(位于2位字段中)和

A 64-bit signed integer that encodes the Kind property in a 2-bit field and the Ticks property in a 62-bit field.

由于 Kind 属性对我们没有用,因此我们可以简单地使用 value&(((1L<<<< 62)-1)来获取 Ticks 属性.

Since the Kind property is useless to us, we can simply mask it out using value & ((1L << 62) - 1) to get the Ticks property.

A 勾号是:

单个刻度表示 100纳秒或1千万分之一秒.毫秒内有 10,000 个滴答声(请参阅

A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond (see TicksPerMillisecond) and 10 million ticks in a second.

此属性的值表示自 0001年1月1日午夜12:00:00以来已经过去的100纳秒间隔的数量.

The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001.

这意味着我们可以这样转换:

Which means we can convert like this:

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的结果可能是错误的.

Warning: The -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.

我们还可以采用其他方式进行转换:

We can also convert the other way:

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


另请参见: Java 8时间-等效于.NET DateTime.MaxValue.Ticks

这篇关于如何将.NET DateTime.toBinary()转换为Java日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆