How do you convert epoch time in C#?

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

    If you want better performance you can use this version.

    public const long UnixEpochTicks = 621355968000000000;
    public const long TicksPerMillisecond = 10000;
    public const long TicksPerSecond = TicksPerMillisecond * 1000;
    
    //[MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static DateTime FromUnixTimestamp(this long unixTime)
    {
        return new DateTime(UnixEpochTicks + unixTime * TicksPerSecond);
    }
    

    From a quick benchmark (BenchmarkDotNet) under net471 I get this number:

            Method |     Mean |     Error |    StdDev | Scaled |
    -------------- |---------:|----------:|----------:|-------:|
             LukeH | 5.897 ns | 0.0897 ns | 0.0795 ns |   1.00 |
          MyCustom | 3.176 ns | 0.0573 ns | 0.0536 ns |   0.54 |
    

    2x faster against LukeH's version (if the performance mater)

    This is similar to how DateTime internally work.

提交回复
热议问题