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; }

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}");
调用结果
