How do you convert epoch time in C#?

后端 未结 14 2484
野的像风
野的像风 2020-11-22 06:51

How do you convert Unix epoch time into real time in C#? (Epoch beginning 1/1/1970)

14条回答
  •  独厮守ぢ
    2020-11-22 07:05

    With all credit to LukeH, I've put together some extension methods for easy use:

    public static DateTime FromUnixTime(this long unixTime)
    {
        var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        return epoch.AddSeconds(unixTime);
    }
    
    public static long ToUnixTime(this DateTime date)
    {
        var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        return Convert.ToInt64((date - epoch).TotalSeconds);
    }
    

    Note the comment below from CodesInChaos that the above FromUnixTime returns a DateTime with a Kind of Utc, which is fine, but the above ToUnixTime is much more suspect in that doesn't account for what kind of DateTime the given date is. To allow for date's Kind being either Utc or Local, use ToUniversalTime:

    public static long ToUnixTime(this DateTime date)
    {
        var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        return Convert.ToInt64((date.ToUniversalTime() - epoch).TotalSeconds);
    }
    

    ToUniversalTime will convert a Local (or Unspecified) DateTime to Utc.

    if you dont want to create the epoch DateTime instance when moving from DateTime to epoch you can also do:

    public static long ToUnixTime(this DateTime date)
    {
        return (date.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
    }
    

提交回复
热议问题