【问题标题】:how to C# convert ulong to DateTime?如何 C# 将 ulong 转换为 DateTime?
【发布时间】:2013-11-18 21:08:13
【问题描述】:

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

ulong timeN = 99844490909448899;//time in nanoseconds

然后我需要将其转换为 DateTime ("MM/dd/yyyy hh:mm:ss") 格式。

我该如何解决这个问题?

【问题讨论】:

  • 99844490909448899几点了?
  • 这是一个unix日期吗?见here
  • @user2964067:持续时间可以用纳秒表示。绝对时间不行。你的参考点是什么?
  • DateTime 没有支持纳秒的分辨率,您必须使用滴答声(滴答声是 100 纳秒)。
  • @user2964067:做var d = new DateTime(timeN/100)。 (因为滴答声以 100 纳秒为间隔)。

标签: c# datetime ulong


【解决方案1】:
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);
}

这给出了日期时间:01 March 2003 14:34:50,使用以下调用:

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

【讨论】:

  • 感谢大卫和博士
猜你喜欢
  • 1970-01-01
  • 2016-07-31
  • 2015-06-12
  • 2015-06-09
  • 1970-01-01
  • 2015-09-29
  • 1970-01-01
  • 2010-10-30
  • 2019-06-24
相关资源
最近更新 更多