美文网首页
关于 C# DateTime.Now.Ticks

关于 C# DateTime.Now.Ticks

作者: By_syk | 来源:发表于2017-09-21 09:57 被阅读958次

学习 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);
}

相关文章

  • 关于 C# DateTime.Now.Ticks

    学习 C# 的过程中时间方法的使用值得一记,尤其是已经熟悉 Java。 先看看文档摘要: DateTime.Tic...

  • 无标题文章

    Aliyun OSS SDK for C# 关于 此C# SDK基于阿里云对象存储服务 API构建。 阿里云对象存...

  • 10月13日-4期C语言学习总结

    总结:今天开始学习C#的课程,代课老师用PPT将.NET和C#做了简述。向我们简介了关于C#的由来及应用。根据老师...

  • 关于C#的Dictionary多线程情况下CPU 100%的问题

    【关于C#的Dictionary多线程情况下CPU 100%的问题】 C#的偶发性 CPU 100%的问题,定位到...

  • JS基础知识

    1.关于script标签 Language:引用的语言 javascript、php、c#、VBSCRIPTSrc...

  • 从零开始学C#--一些其它的问题

    本篇属于:从零开始学C# | 基础篇 | 06 到本篇为止,C#的基础篇就完结了,即将进入到面向对象的学习。 关于...

  • U3D_03_13

    关于C#的编程知识 注意了:C#扩展方法的声明必须是静态类和静态方法,你看这里都标注了static就是这个原因,使...

  • protobuf官方C#版本的额外扩展方案

    根据上一篇关于protobuf的官方C#版本额外扩展记录,当改造完成后,结合实际C#开发(我主要使用Unity进行...

  • C#获取http header信息的代码

    如下资料是关于C#获取http header信息的内容。 public Dictionary GetHTTPRe...

  • C# 6/7 新功能

    C#新功能 一、C#历史演变 C# 1,Visual Studio .NET 2002: C# 初版。 C# 1....

网友评论

      本文标题:关于 C# DateTime.Now.Ticks

      本文链接:https://www.haomeiwen.com/subject/ysfzsxtx.html