C# 如何将ulong转换为DateTime?

C# 如何将ulong转换为DateTime?,c#,datetime,ulong,C#,Datetime,Ulong,在我的C#程序中,我从PLC接收datetime。它正在以“ulong”格式发送数据。 如何将ulong转换为DateTime格式? 例如,我收到: ulong timeN = 99844490909448899;//time in nanoseconds 然后我需要将其转换为DateTime(“MM/dd/yyyy hh:MM:ss”)格式 我怎样才能解决这个问题 static DateTime GetDTCTime(ulong nanoseconds, ulong ticksPerNano

在我的C#程序中,我从PLC接收datetime。它正在以“ulong”格式发送数据。 如何将ulong转换为DateTime格式? 例如,我收到:

ulong timeN = 99844490909448899;//time in nanoseconds
然后我需要将其转换为DateTime(“MM/dd/yyyy hh:MM:ss”)格式

我怎样才能解决这个问题

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);
}
这将使用以下调用提供日期时间:
2003年3月1日14:34:50

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

99844490909448899是几点?是unix日期吗?请参见@user2964067:持续时间可以用纳秒表示。绝对时间不能。您的参考点是什么?DateTime没有支持纳秒的分辨率,您必须使用刻度(刻度为100纳秒)。@user2964067:Do
var d=new DateTime(timeN/100)
。(因为滴答声以100纳秒为间隔)。由于参考点以UTC为单位,因此可能需要显式地将种类设置为UTC(例如,
pointOfReference=new DateTime(2000,1,1,0,0,0,DateTimeKind.UTC)
),特别是在需要与本地时间进行转换的情况下。感谢David和drf