Parsing unix time in C#

后端 未结 9 626
悲&欢浪女
悲&欢浪女 2020-11-30 10:13

Is there a way to quickly / easily parse Unix time in C# ? I\'m brand new at the language, so if this is a painfully obvious question, I apologize. IE I have a string in th

相关标签:
9条回答
  • 2020-11-30 10:41

    Hooray for MSDN DateTime docs! Also see TimeSpan.

    // First make a System.DateTime equivalent to the UNIX Epoch.
    System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
    // Add the number of seconds in UNIX timestamp to be converted.
    dateTime = dateTime.AddSeconds(numSeconds);
    // Then add the number of milliseconds
    dateTime = dateTime.Add(TimeSpan.FromMilliseconds(numMilliseconds));
    
    0 讨论(0)
  • 2020-11-30 10:45

    This is a very common thing people in C# do, yet there is no library for that.

    I created this mini library https://gist.github.com/1095252 to make my life (I hope yours too) easier.

    0 讨论(0)
  • 2020-11-30 10:46

    Simplest way is probably to use something like:

    private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 
                                                          DateTimeKind.Utc);
    
    ...
    public static DateTime UnixTimeToDateTime(string text)
    {
        double seconds = double.Parse(text, CultureInfo.InvariantCulture);
        return Epoch.AddSeconds(seconds);
    }
    

    Three things to note:

    • If your strings are definitely of the form "x.y" rather than "x,y" you should use the invariant culture as shown above, to make sure that "." is parsed as a decimal point
    • You should specify UTC in the DateTime constructor to make sure it doesn't think it's a local time.
    • If you're using .NET 3.5 or higher, you might want to consider using DateTimeOffset instead of DateTime.
    0 讨论(0)
提交回复
热议问题