如何将Unix时间戳转换为日期时间,反之亦然?这里有一个示例代码,但随后它开始讨论毫秒/纳秒问题。同样的问题也出现在MSDN上,自C#中的Unix时代以来的秒数.到目前为止,这就是我所得到的: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);
}}
4 回答
人到中年有点甜
TA贡献1895条经验 获得超7个赞
public static DateTime UnixTimeStampToDateTime( double unixTimeStamp ){ // Unix timestamp is seconds past epoch System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc); dtDateTime = dtDateTime.AddSeconds( unixTimeStamp ).ToLocalTime(); return dtDateTime;}
public static DateTime JavaTimeStampToDateTime( double javaTimeStamp ){ // Java timestamp is milliseconds past epoch System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc); dtDateTime = dtDateTime.AddMilliseconds( javaTimeStamp ).ToLocalTime(); return dtDateTime;}
牛魔王的故事
TA贡献1830条经验 获得超3个赞
以秒为单位的Unix时间到UTC DateTimeOffset
:
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(1000);
DateTimeOffset
以秒为单位的Unix时间:
long unixTimeStampInSeconds = dateTimeOffset.ToUnixTimeSeconds();
Unix时间(毫秒到UTC) DateTimeOffset
:
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(1000000);
DateTimeOffset
以毫秒为单位的Unix时间:
long unixTimeStampInMilliseconds = dateTimeOffset.ToUnixTimeMilliseconds();
DateTimeOffset
DateTime
DateTimeOffset.UtcDateTime
DateTimeOffset.LocalDateTime
DateTime dateTime = dateTimeOffset.UtcDateTime;
慕仙森
TA贡献1827条经验 获得超7个赞
public static double DateTimeToUnixTimestamp(DateTime dateTime){ return (TimeZoneInfo.ConvertTimeToUtc(dateTime) - new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;}
- 4 回答
- 0 关注
- 1187 浏览
添加回答
举报
0/150
提交
取消