将纪元/unix 转换为日期时间 [英] Convert epoch/unix to Datetime

查看:47
本文介绍了将纪元/unix 转换为日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题不是重复的,这个问题说明了转换方法的问题,而不是如何执行转换.完整阅读问题.

我有一个时间戳,我认为它是一个 unix 时间戳,当使用以下转换器时,它会正确转换时间戳

I have a timestamp which I believe is a unix time stamp, when using the following converter it correctly converts the stamp

值:1365151714493

Value: 1365151714493

http://www.epochconverter.com/

我环顾四周,发现了一个示例关于如何将其转换为日期时间对象并且该方法看起来很简单,创建一个日期时间对象并将日期设置为 1/1/1970 的可能之夜并将值添加为秒:

I have looked around and found an example on how to convert this to a datetime obect and the method seems simple, create a datetime object and set the date to the might night on 1/1/1970 and add the value as second:

public static DateTime? ConvertUnixTimeStamp(string unixTimeStamp)
{
    return new DateTime(1970, 1, 1, 0, 0).AddSeconds(Convert.ToDouble(unixTimeStamp));
}

问题是每次我用上面的值调用这个方法时,我都会得到一个超出范围异常的值.

The problem is everytime I call this mehod with the value above I get a value out of range exception.

我需要先对值做些什么吗?字符串转换为双重确定.调用AddSeconds(double)方法

Do I need to do anything with the value first? the string converts to a double ok. the exception is thrown when calling the AddSeconds(double) methos

推荐答案

那个时间戳 (1365151714493) 以毫秒为单位,而不是秒.您需要除以 1000 或使用 AddMilliseconds 代替.如果将其视为秒,则它是未来大约 43,259(粗略计算)年的日期.这超出了 DateTime 的范围,其中 在 10000 年达到最大值,从而抛出 ArgumentOutOfRangeException.

That timestamp (1365151714493) is in milliseconds, not seconds. You'll need to divide by 1000 or use AddMilliseconds instead. If it's treated as seconds, it's a date some 43,259 (rough calculation) years in the future. This is beyond the range of DateTime which maxes out at the year 10000, thus throwing the ArgumentOutOfRangeException.

public static DateTime? ConvertUnixTimeStamp(string unixTimeStamp)
{
    return new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(Convert.ToDouble(unixTimeStamp));
}

您可能还想考虑按照 V4Vendetta 的建议将其强制为格林威治标准时间.此外,如果您希望混合使用多种格式(秒或毫秒),那么对解析值进行快速大小检查可能是明智之举.

You may also want to consider forcing it to GMT as V4Vendetta suggested. In addition, if you expect to have a mix of formats (seconds OR milliseconds) perhaps a quick size check on the parsed value might be prudent.

这篇关于将纪元/unix 转换为日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆