【问题标题】:Get current time as ulong amount of minutes since 01.01.2001 00:00 in c#在 c# 中获取当前时间为自 01.01.2001 00:00 以来的 ulong 分钟数
【发布时间】:2013-10-17 16:45:23
【问题描述】:

如何在 c# 中获取自 01.01.2001 00:00 以来的 ulong 分钟数的当前 UTC 时间?我知道它涉及 DateTime.UtcNow 属性,但是如何在几分钟内获得偏移量?

【问题讨论】:

  • 那么到目前为止您尝试过什么? (提示 - 您可以从另一个中减去一个 DateTime 以获得 TimeSpan...)

标签: c# datetime utc


【解决方案1】:

你可以使用:

ulong totalMinutes = (ulong) (DateTime.UtcNow - new DateTime(2001,1,1,0,0,0,0, DateTimeKind.Utc)).TotalMinutes;

【讨论】:

  • @ScottChamberlain:不在DateTime 的范围内。 double 在尾数中有足够的位来正确表示 DateTime 整个范围内的每一个可能的分钟数。
【解决方案2】:

您可以将 DateTime.UtcNow 函数与 TimeSpan 结合使用:

        DateTime reference = new DateTime(2001, 01, 01, 0, 0, 0, DateTimeKind.Utc);
        TimeSpan duration = new TimeSpan(DateTime.UtcNow.Ticks - reference.Ticks);
        ulong minutesCount = Convert.ToUInt64(duration.TotalMinutes);

【讨论】:

  • 为什么要使用刻度而不是直接减去时间跨度?
  • new TimeSpan(DateTime.UtcNow.Ticks - reference.Ticks); 这一步真的没必要。要么直接从刻度到分钟 ((DateTime.UtcNow.Ticks - reference.Ticks) / 10000 / 1000 / 60),要么直接减去 DateTime。
猜你喜欢
  • 2021-09-19
  • 2021-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多