验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

C#时间戳转换代码怎么写

阅读:549 来源:乙速云 作者:代码code

C#时间戳转换代码怎么写

代码如下:

        /// 
        /// 将时间转时间戳换
        /// 有效范围1970-01-01 08:00:00~~2100-01-01 08:00:00 (范围可改)
        /// 
        /// 要转换的时间
        /// 输出转换长度 
        /// 输出时间戳
        /// 
        public bool ToTimeStamp(DateTime time,int length, out long timestamp)
        {
            timestamp = 0;
            if (length == 11)
            {
                timestamp = Convert.ToInt64((time - (TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)))).TotalSeconds);
                return (timestamp > 0 && timestamp <= 4102444800);//范围设定
            }
            else if (length == 13)
            {
                timestamp = Convert.ToInt64((time - (TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)))).TotalMilliseconds);
                return (timestamp > 0 && timestamp <= 4102444800000);//范围设定
            }
            else
                return false;
        }
        /// 
        /// 将时间戳换为时间转
        /// 有效范围1970-01-01 08:00:00~~2100-01-01 08:00:00 (范围可改)
        /// 
        /// 要转换的时间戳
        /// 要转换长度
        /// 输出时间
        /// 
        public bool ToDateTime(long timestamp, int length, out DateTime time)
        {
            time = DateTime.Now;
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));//当地时区
            if (length == 11)
            {
                time = startTime.AddSeconds(timestamp);
                return (timestamp > 0 && timestamp <= 4102444800);//范围设定
            }
            else if (length == 13)
            {
                time = startTime.AddMilliseconds(timestamp);
                return (timestamp > 0 && timestamp <= 4102444800000);//范围设定
            }
            else return false;
        }

C#时间戳转换代码怎么写

            DateTime dt=DateTime.Now;
            new MyThread().ToTimeStamp(dt, 11, out long timestamp1);
            new MyThread().ToTimeStamp(dt, 13, out long timestamp2);
            new MyThread().ToDateTime(timestamp1, 11, out DateTime time1);
            new MyThread().ToDateTime(timestamp2, 13, out DateTime time2);
            Console.WriteLine("转换的时间"+dt);
            Console.WriteLine($"11位的时间戳:{timestamp1}");
            Console.WriteLine($"13位的时间戳:{timestamp2}");
            Console.WriteLine($"11位的时间戳转时间:{time1}");
            Console.WriteLine($"13位的时间戳转时间:{time2}");

C#时间戳转换代码怎么写

调用结果

C#时间戳转换代码怎么写

分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>