简体   繁体   中英

How to convert 16 digit epoch timestamp to datetime in c# without losing microseconds precision

    public static DateTime ToDateTimeForEpochMSec(this double microseconds)
    {
        var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        DateTime tempDate = epoch.AddMilliseconds(microseconds / 1000);
        return tempDate;
    }  

tried using this code but losing microseconds precison in the datetime

You need to adjust your code to handle microseconds. We know that 1000 microseconds = 1 millisecond, therefore 1/1000th of a millisecond is a microsecond. Now, after AddMilliseconds , the next level of precision that DateTime supports is Ticks , so we'll have to use that.

We can find the number of ticks in a millisecond by using TimeSpan :

long ticksPerMillisecond = TimeSpan.TicksPerMillisecond;

If 1 microsecond is 1/1000th of a millisecond, then it stands to reason that we need 1/1000th of the ticks to represent a microsecond. The documentation defines a tick as:

one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond (see TicksPerMillisecond) and 10 million ticks in a second.

We should therefore be safe to use integer division to divide by 1000:

long ticksPerMicrosecond = TimeSpan.TicksPerMillisecond / 1000;

Now we can convert the number of microseconds into ticks:

long ticks = (long)(microseconds * ticksPerMicrosecond);

And add it to the epoch:

DateTime tempDate = epoch.AddTicks(ticks);

Putting it all together we get:

public static DateTime ToDateTimeForEpochMSec(this double microseconds)
{
    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    long ticksPerMicrosecond = TimeSpan.TicksPerMillisecond / 1000;
    long ticks = (long)(microseconds * ticksPerMicrosecond);
    DateTime tempDate = epoch.AddTicks(ticks);
    return tempDate;
}  

Try it online

By the way, I'm not sure why microseconds is a double here. It seems like it would be fine as a long .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM