有这个示例代码,但它开始谈论毫秒/纳秒问题。
同样的问题在 MSDN 上, Seconds since the Unix epoch in C# 。
这是我到目前为止所得到的:
public Double CreatedEpoch { get { DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime(); TimeSpan span = (this.Created.ToLocalTime() - epoch); return span.TotalSeconds; } set { DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime(); this.Created = epoch.AddSeconds(value); } }
这是您需要的:
public static DateTime UnixTimeStampToDateTime( double unixTimeStamp ) { // Unix timestamp is seconds past epoch DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); dateTime = dateTime.AddSeconds( unixTimeStamp ).ToLocalTime(); return dateTime; }
或者,对于 Java(这是不同的,因为时间戳以毫秒为单位,而不是秒):
public static DateTime JavaTimeStampToDateTime( double javaTimeStamp ) { // Java timestamp is milliseconds past epoch DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); dateTime = dateTime.AddMilliseconds( javaTimeStamp ).ToLocalTime(); return dateTime; }