C# 中的 Unix 时间转换
我正在尝试以unix时间获取GMT。我使用以下代码:
public static long GetGMTInMS()
{
var unixTime = DateTime.Now.ToUniversalTime() -
new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return (long)unixTime.TotalMilliseconds;
}
然后,为了将 unix 时间转换回 DatTime 对象,我使用以下代码:
public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
{
System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
dtDateTime = dtDateTime.AddMilliseconds(unixTimeStamp).ToLocalTime();
return dtDateTime;
}
当我运行它时,GetGMTInMS()
1320249196267
。当我将其传递给 UnixTimeStampToDateTime()
时,我得到 {11/2/2011 11:53:16 AM}
这很好。这是我运行代码的正确时间。我遇到的问题是当我尝试将 1320249196267
放入 unix 时间转换器时,例如 this,它返回完全错误的时间。
另一个问题是我在东部时区。这返回了我所在时区的时间。这是 DateTime
对象处理的事情还是我没有得到 GMT。
I am trying to get the GMT in unix time. I use the following code:
public static long GetGMTInMS()
{
var unixTime = DateTime.Now.ToUniversalTime() -
new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return (long)unixTime.TotalMilliseconds;
}
To then convert the unix time back to a DatTime object, I use this:
public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
{
System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
dtDateTime = dtDateTime.AddMilliseconds(unixTimeStamp).ToLocalTime();
return dtDateTime;
}
When I run it, the GetGMTInMS()
1320249196267
. When I pass it to UnixTimeStampToDateTime()
I get {11/2/2011 11:53:16 AM}
Which is fine. That is the correct time fro when I ran my code. The issue I have is when I try and put 1320249196267
into an unix time converter, such as this, it returns the totally wrong time.
The other issue, is i am in the eastern time zone. This returned the time in my time zone. Is this something that the DateTime
object handles or am I not getting the GMT.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在大多数情况下,“Unix 时间戳”是指自纪元以来的秒,而不是毫秒......小心!然而,像 Java 这样的东西使用“自纪元以来的毫秒”,这可能是您实际上关心的 - 尽管您展示了工具。这实际上取决于您的需要。
此外,您不应该按照当地时间做任何事情。始终坚持世界时间。
我会:
"Unix timestamp" means seconds since the epoch in most situations rather than milliseconds... be careful! However, things like Java use "milliseconds since the epoch" which may be what you actually care about - despite the tool you showed. It really depends on what you need.
Additionally, you shouldn't be doing anything with local time. Stick to universal time throughout.
I would have:
UNIX 时间是自 1970 年 1 月 1 日以来的秒数,而不是毫秒。将代码更改为使用秒而不是毫秒,它应该可以工作,
UNIX time is seconds since 1/1/1970, not milliseconds. Change the code to use seconds rather than milliseconds and it should work,