本篇文章主要介绍了C# DateTime与时间戳(11位与13)转换实例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧C#
/// <summary> /// 将时间转时间戳换 /// 有效范围1970-01-01 08:00:00~~2100-01-01 08:00:00 (范围可改) /// </summary> /// <param name="time">要转换的时间</param> /// <param name="length">输出转换长度</param> /// <param name="timestamp">输出时间戳</param> /// <returns></returns> 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; } /// <summary> /// 将时间戳换为时间转 /// 有效范围1970-01-01 08:00:00~~2100-01-01 08:00:00 (范围可改) /// </summary> /// <param name="timestamp">要转换的时间戳</param> /// <param name="length">要转换长度</param> /// <param name="time">输出时间</param> /// <returns></returns> 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; }
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}");
调用结果