obsidian/笔记文件/2.笔记/时间戳差值 秒为单位.md
2025-03-26 00:02:56 +08:00

2.0 KiB
Raw Permalink Blame History

#unity/日常积累

默认的时间戳,不是以秒为单位的,搭配换算逻辑; 获得精准的 以秒为单位的时间戳,不同平台或者编程语言,获取方式,会有差异

参考:

!Pasted image 20240912181905.png

在Unity中因为是Csharp所有获取方式参考

long startTime = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;

以秒为单位,计算时间戳的差值


    /// <summary>
    /// 将秒数时间戳转换为多久之前。传入时间戳t(t= 当前时间戳() - 指定时间的时间戳 )
    /// </summary>
    /// <param name="t"></param>
    /// <returns></returns>
    public static string GetTimeLongAgo(double t)
    {
        string str = "";
        double num;
        if (t < 60)
        {
            str = string.Format("{0}秒", t);
        }
        else if (t >= 60 && t < 3600)
        {
            num = Math.Floor(t / 60);
            str = string.Format("{0}分钟", num);
        }
        else if (t >= 3600 && t < 86400)
        {
            num = Math.Floor(t / 3600);
            str = string.Format("{0}小时", num);
        }
        else if (t > 86400 && t < 2592000)
        {
            num = Math.Floor(t / 86400);
            str = string.Format("{0}天", num);
        }
        else if (t > 2592000 && t < 31104000)
        {
            num = Math.Floor(t / 2592000);
            str = string.Format("{0}月", num);
        }
        else
        {
            num = Math.Floor(t / 31104000);
            str = string.Format("{0}年", num);
        }
        return str;
    }

在Update函数里面鼠标左键点击一次对比一次时间差值

        private void Update()
        {
            if (Input.GetMouseButtonDown(0))
            {
                Debug.Log(GetTimeLongAgo((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000 - startTime));
            }
        }

运行,测试正常

!Pasted image 20240912182236.png