深入Unix时间戳与C# DateTime时间类型互换的详解

本篇文章是对Unix时间戳与C# DateTime时间类型互换进行了详细的分析介绍,需要的朋友参考下

Unix时间戳最小单位是秒,开始时间为格林威治标准时间1970-01-01 00:00:00
ConvertIntDateTime方法的基本思路是通过获取本地时区表示Unixk开始时间,加上Unix时间值(即过去的秒数).
ConvertDateTimeInt方法的基本思路是通过刻度数差,再把刻度数转换为秒数,当然要说明的是,我这里返回的是double类型,意义上并非是真正的Unix时间戳格式。
要获取真正Unix时间戳的,只获取整数部分就可以了。
复制代码 代码如下:

dangranusing System;
using System.Collections.Generic;
using System.Text;
namespace WWFramework.DateTimes
{
    ///
    /// 时间相关函数
    ///

    public static class Function
    {
        ///
        /// 将Unix时间戳转换为DateTime类型时间
        ///

        /// double 型数字
        /// DateTime
        public static System.DateTime ConvertIntDateTime(double d)
        {
            System.DateTime time = System.DateTime.MinValue;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            time = startTime.AddSeconds(d);
            return time;
        }
        ///
        /// 将c# DateTime时间格式转换为Unix时间戳格式
        ///

        /// 时间
        /// double
        public static double ConvertDateTimeInt(System.DateTime time)
        {
            double intResult = 0;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            intResult = (time - startTime).TotalSeconds;
            return intResult;
        }
    }
}

以上就是深入Unix时间戳与C# DateTime时间类型互换的详解的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 其他教程