本篇内容介绍了“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}");
调用结果