欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Unity里使用C#获取时间戳

程序员文章站 2022-04-01 10:30:18
时间戳是个常用的东西。由于C# 没有直接获得时间戳的方法,所以每次都上网随便找个算法贴上。但是今天发现网上流行的两种算法,得出的时间戳居然不一致。哪一种更靠谱呢?放到unity里测试一下: // Start is called before the first frame update void Start() { Int64 time_stamp = GetTimeStamp(); Debug.Log("time_stamp 10: " +...

时间戳是个常用的东西。由于C# 没有直接获得时间戳的方法,所以每次都上网随便找个算法贴上。这次干脆自己记录一下:

放到unity里测试一下:

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        
    }

    // 获取当前时间戳--10位时间戳, 注意,int32的时间戳, 只能到2038年, 所以采用了long(int64) 
    public long GetTimeStamp()
    {
        // 注意, 如果直接使用DateTime.Now, 会有系统时区问题, 导致误差
        TimeSpan timeStamp = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        return Convert.ToInt64(timeStamp.TotalSeconds);
    }

    // 获取当前时间戳, 包含毫秒数
    private double GetTimeStampMs()
    {
        double timeStamp = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000) * 0.001;
        return timeStamp;
    }

运行:

Unity里使用C#获取时间戳

emmmm, 没错。

我们再打开python试一下:

Unity里使用C#获取时间戳

跟python版本的时间戳可以匹配。

 

 

 

本文地址:https://blog.csdn.net/chenggong2dm/article/details/110168184

相关标签: Unity 架构