how to C# convert ulong to DateTime?

8.2k Views Asked by At

In my C# program I'm receiving datetime from a PLC. It is sending data in "ulong" format. How can I convert ulong to DateTime format? for example I am receiving:

ulong timeN = 99844490909448899;//time in nanoseconds

then I need to convert it into DateTime ("MM/dd/yyyy hh:mm:ss") format.

How can I solve this?

1

There are 1 best solutions below

2
On BEST ANSWER
static DateTime GetDTCTime(ulong nanoseconds, ulong ticksPerNanosecond)
{
    DateTime pointOfReference = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    long ticks = (long)(nanoseconds / ticksPerNanosecond);
    return pointOfReference.AddTicks(ticks);
}

static DateTime GetDTCTime(ulong nanoseconds)
{
    return GetDTCTime(nanoseconds, 100);
}

This gives a date time of: 01 March 2003 14:34:50 using the following call:

ulong timeN = 99844490909448899;//time in nanoseconds
var theDate = GetDTCTime(timeN);