How do you convert epoch time in C#?

后端 未结 14 2496
野的像风
野的像风 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:16

    Use the method DateTimeOffset.ToUnixTimeMilliseconds() It returns the number of milliseconds that have elapsed since 1970-01-01T00:00:00.000Z.

    This is only supported with Framework 4.6 or higher

    var EPOCH = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
    

    It's well documented here DateTimeOffset.ToUnixTimeMilliseconds

    The other way out is to use the following

    long EPOCH = DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1,0,0,0,0).Ticks;
    

    To get the EPOCH with seconds only you may use

     var Epoch = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
    

    and convert the Epoch to DateTime with the following method

    private DateTime Epoch2UTCNow(int epoch) 
    {
        return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(epoch); 
    }
    

提交回复
热议问题