how to C# convert ulong to DateTime?
Asked Answered
B

1

3

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?

Brazier answered 7/11, 2013 at 9:30 Comment(12)
What time is 99844490909448899?Burmeister
Is it a unix date? See hereBurmeister
Thanks for the comment. no, it is Distributed Clock System Time (known as DC Time for short) in the form of a linear, 64-bit unsigned integer value. The time is expressed in nanoseconds.Brazier
@user2964067: Duration can be expressed in nanoseconds. Absolute time can not. What is your point of reference?Fairy
You have to add that to your question. If that value can be transformed to 100-nanosecond intervals that have elapsed since January 1, 0001 at 00:00:00.000 in the Gregorian calendar. you can use this DateTime constructors that takes a long.Burmeister
As of this page (german), the point of reference is 2000/01/01 00:00 UTC.Tetrode
Dear Gene, yes you are true. So how can I convert that in c# to DateTime?Brazier
DateTime does not have the resolution to support nanoseconds, you have to work with ticks (a tick is 100 nanoseconds).Commandment
@user2964067: Do var d = new DateTime(timeN/100). (Because ticks is in 100 nanoseconds interval).Thierry
@Thierry That gives the wrong date because DateTime(long) has a different reference date. The best way to solve it is probably to create a datetime for the reference date, then a timespan with timeN/100, then add the timespan to the reference datetime.Commandment
Dear PMF, DateTime has no constructor for ulong.Brazier
@user2964067: There is one for Int64 ("signed long"). Shouldn't matter. But I was really overlooking the fact that the reference time is different. See the answer below.Thierry
D
5
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);
Duren answered 7/11, 2013 at 10:6 Comment(2)
Since the point of reference is in UTC, it may be desirable to explicitly set the Kind to UTC (e.g., pointOfReference = new DateTime(2000,1,1,0,0,0,DateTimeKind.Utc)), particularly if conversions to and from local time are needed.Singapore
Thanks to David and drfBrazier

© 2022 - 2024 — McMap. All rights reserved.