Unix时间转换在C# [英] Unix time conversions in C#

查看:158
本文介绍了Unix时间转换在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让GMT在UNIX时间。我用下面的code:

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;
        }

要那么UNIX时间转换回DatTime对象,我用这样的:

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;
        }

当我运行它时, GetGMTInMS() 1320249196267 。当我把它传递给 UnixTimeStampToDateTime()我得到 {2011年11月2日上午11时53分16秒}

When I run it, the GetGMTInMS() 1320249196267. When I pass it to UnixTimeStampToDateTime() I get {11/2/2011 11:53:16 AM}

这很好。这是正确的时间来回,当我跑我的code。这个问题我已经是当我尝试把 1320249196267 成UNIX时间转换器,如的这个,它返回完全错误的时间。

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.

另外一个问题,就是我在东部时区。这回来的时候在我的时区。这是不是该的DateTime 对象处理还是我没有得到的格林尼治标准​​时间。

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.

推荐答案

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.

我会:

private static readonly DateTime UnixEpoch =
    new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

public static long GetCurrentUnixTimestampMillis()
{
    return (long) (DateTime.UtcNow - UnixEpoch).TotalMilliseconds;
}

public static DateTime DateTimeFromUnixTimestampMillis(long millis)
{
    return UnixEpoch.AddMilliseconds(millis);
}

public static long GetCurrentUnixTimestampSeconds()
{
    return (long) (DateTime.UtcNow - UnixEpoch).TotalSeconds;
}

public static DateTime DateTimeFromUnixTimestampSeconds(long seconds)
{
    return UnixEpoch.AddSeconds(seconds);
}

这篇关于Unix时间转换在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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