C#使用时间戳

示例

在.NETCore中TimeZone被标记为过时,所以有了下面的新方法

[Obsolete("System.TimeZone has been deprecated.  Please investigate the use of System.TimeZoneInfo instead.")]
public abstract class TimeZone

代码

//旧方法
{
	DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
	DateTime now = DateTime.Now;
	Console.WriteLine(now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
	Console.WriteLine(now.Kind);

	//转换ts
	long ts1 = (long)(now - startTime).TotalSeconds;
	Console.WriteLine(ts1);
	long ts2 = (long)(now - startTime).TotalMilliseconds;
	Console.WriteLine(ts2);

	//ts还原时间
	DateTime dt1 = startTime.AddSeconds(ts1);
	Console.WriteLine(dt1.ToString("yyyy-MM-dd HH:mm:ss.fff"));
	DateTime dt2 = startTime.AddMilliseconds(ts2);
	Console.WriteLine(dt2.ToString("yyyy-MM-dd HH:mm:ss.fff"));
}

Console.WriteLine(" ===================================================> ");

//新方法
{
	DateTime currentTime = DateTime.UtcNow;
	DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
	TimeSpan elapsedTime = currentTime - unixEpoch;
	Console.WriteLine(currentTime.ToString("yyyy-MM-dd HH:mm:ss.fff"));
	Console.WriteLine(currentTime.Kind);
	Console.WriteLine(unixEpoch.ToString("yyyy-MM-dd HH:mm:ss.fff"));
	Console.WriteLine(unixEpoch.Kind);

	//转换ts
	long ts1 = (long)elapsedTime.TotalSeconds;
	Console.WriteLine(ts1);
	long ts2 = (long)elapsedTime.TotalMilliseconds;
	Console.WriteLine(ts2);

	//ts还原时间
	DateTime dt1 = unixEpoch.AddSeconds(ts1);
	Console.WriteLine(dt1.AddHours(8).ToString("yyyy-MM-dd HH:mm:ss.fff"));
	DateTime dt2 = unixEpoch.AddMilliseconds(ts2);
	Console.WriteLine(dt2.AddHours(8).ToString("yyyy-MM-dd HH:mm:ss.fff"));
}

结果

2025-12-29 13:19:22.815
Local
1766985562
1766985562815
2025-12-29 13:19:22.000
2025-12-29 13:19:22.815
 ===================================================>
2025-12-29 05:19:22.816
Utc
1970-01-01 00:00:00.000
Utc
1766985562
1766985562816
2025-12-29 13:19:22.000
2025-12-29 13:19:22.816

posted @ 2020-06-30 13:15  我有我奥妙  阅读(2385)  评论(0)    收藏  举报