关于 C# DateTime.Now.Ticks

字数 259阅读 3443

学习 C# 的过程中时间方法的使用值得一记,尤其是已经熟悉 Java。

先看看文档摘要:

DateTime.Ticks
Gets the number of ticks that represent the date and time of this instance.

Remarks
A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond, or 10 million ticks in a second.
The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001 (0:00:00 UTC on January 1, 0001, in the Gregorian calendar), which represents DateTime.MinValue. It does not include the number of ticks that are attributable to leap seconds.

https://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx

.Ticks 得到的值是自公历 0001-01-01 00:00:00:000 至此的以 100 ns(即 1/10000 ms)为单位的时间数。

而在 Java 中,System.currentTimeMillis() 值是自公历 1970-01-01 00:00:00:000 至此的以 ms 为单位的时间数。区别有二。如果希望与 System.currentTimeMillis() 一致,则

// Same as Java's System.currentTimeMillis()
public static long CurrentTimeMillis() {
    return ToUnixMillis(DateTime.Now);
}

private static long ToUnixMillis(DateTime date) {
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    TimeSpan diff = date.ToUniversalTime() - origin;
    return (long)diff.TotalMilliseconds;
}

相反,如果希望将 Java 的毫秒时间转化为 C# 的 DateTime,则

public static DateTime FromUnixMillis(long unixMillis) {
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    return origin.AddMilliseconds(unixMillis);
}

推荐阅读更多精彩内容