Search code examples
c#unix-timestamp

Parsing unix time in C#


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 the format [seconds since Epoch].[milliseconds]. Is there an equivalent to Java's SimpleDateFormat in C# ?


Solution

  • 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.