如何使用Ruby将时间从.net时代转换为Unix时代?

时间:2022-08-24 11:26:50

I have an input timestamp from C# (.NET epoch: 00:00:00 (midnight), January 1, 0001) and I want to output it in Ruby world (Unix epoch: 00:00:00 UTC on 1 January 1970).

我有一个来自C#的输入时间戳(.NET epoch:00:00:00(午夜),0001年1月1日),我想在Ruby世界中输出它(Unix纪元:1970年1月1日00:00:00 UTC) 。

The input timestamp is given in UTC, and derived from .NET's DateTime(Int64), which is "a date and time expressed in the number of 100-nanosecond intervals that have elapsed since January 1, 0001 at 00:00:00.000 in the Gregorian calendar."

输入时间戳以UTC格式给出,并从.NET的DateTime(Int64)派生,这是一个日期和时间,表示为自0001年1月1日(00:00:00:00000)以来经过的100纳秒间隔的数量。公历。”

The input timestamp: 634891434586852680

输入时间戳:634891434586852680

Output should be 2012-NOV-21 a bit after 5pm PST.

太平洋标准时间下午5点之后输出应该是2012-NOV-21。

1 个解决方案

#1


3  

input =                         634891434586852680
UNIX_EPOCH_IN_100NS_INTERVALS = 621355968000000000

Time.at((input-UNIX_EPOCH_IN_100NS_INTERVALS)*1e-7).utc.getlocal
 => 2012-11-21 17:10:58 -0800

In Ruby, Time is stored internally as the number of seconds with fraction since the Epoch, January 1, 1970 00:00 UTC. Therefore we must convert from 100-nanosecond intervals to seconds.

在Ruby中,Time自内部存储为自1970年1月1日00:00 UTC以来的分数以来的分数。因此,我们必须将100纳秒间隔转换为秒。

The conversion factor of 1e-7 is 1e2/1e9 which is 100/1000000000 which can be explained as:

转换因子1e-7是1e2 / 1e9,即100/1000000000,可以解释为:

X intervals * 100ns/interval * 1s/1000000000ns

The intervals cancel themselves out, as do the nanoseconds, and we are left with seconds; and 100/1000000000 seconds is 1e2/1e9 seconds which is 1e-7 seconds.

间隔取消了,纳秒也是如此,我们留下了几秒钟; 100/1000000000秒是1e2 / 1e9秒,即1e-7秒。

#1


3  

input =                         634891434586852680
UNIX_EPOCH_IN_100NS_INTERVALS = 621355968000000000

Time.at((input-UNIX_EPOCH_IN_100NS_INTERVALS)*1e-7).utc.getlocal
 => 2012-11-21 17:10:58 -0800

In Ruby, Time is stored internally as the number of seconds with fraction since the Epoch, January 1, 1970 00:00 UTC. Therefore we must convert from 100-nanosecond intervals to seconds.

在Ruby中,Time自内部存储为自1970年1月1日00:00 UTC以来的分数以来的分数。因此,我们必须将100纳秒间隔转换为秒。

The conversion factor of 1e-7 is 1e2/1e9 which is 100/1000000000 which can be explained as:

转换因子1e-7是1e2 / 1e9,即100/1000000000,可以解释为:

X intervals * 100ns/interval * 1s/1000000000ns

The intervals cancel themselves out, as do the nanoseconds, and we are left with seconds; and 100/1000000000 seconds is 1e2/1e9 seconds which is 1e-7 seconds.

间隔取消了,纳秒也是如此,我们留下了几秒钟; 100/1000000000秒是1e2 / 1e9秒,即1e-7秒。