Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to C# convert ulong to DateTime?

Tags:

c#

datetime

ulong

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?

like image 704
Balu Avatar asked Nov 19 '25 11:11

Balu


1 Answers

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);
like image 175
David Martin Avatar answered Nov 21 '25 00:11

David Martin