使用有效的Double向DateTime添加秒可导致ArgumentOutOfRangeException

以下代码崩溃和烧伤,我不明白为什么:

DateTime dt = new DateTime(1970,1,1,0,0,0,0, DateTimeKind.Utc); double d = double.Parse("1332958778172"); Console.Write(dt.AddSeconds(d)); 

有人能告诉我发生了什么事吗? 我似乎无法弄清楚为什么……

编辑

这个值来自Salesforce REST API,据我所知,这是一个Unix纪元时间戳。 “令牌问题的时间,表示为自Unix纪元(1970年1月1日00:00:00 UTC)以来的秒数。”

事实上,当执行OAuth请求时,Salesforce REST API会为issued_at字段发送毫秒数据 ,因为他们说他们正在发送秒数…

正如其他人所说,问题是价值太大。

看了之后,我相信它代表了自Unix时代以来的毫秒 ,而不是秒,所以你想要:

 DateTime dt = new DateTime(1970,1,1,0,0,0,0, DateTimeKind.Utc); double d = double.Parse("1332958778172"); // Or avoid parsing if possible :) Console.Write(dt.AddMilliseconds(d)); 

要么是这个,要么在调用AddSeconds之前除以1000 – 但显然会丢失数据。

您添加的值会导致日期超出DateTime支持的有效日期范围。

DateTime支持01/01/0001 00:00:00至31/12/9999 23:59:59。

1332958778172/3600/24/365的简单计算给出了42267年。

我认为双重价值确实太大了。 它代表超过42,267年(如果我的数学是正确的),DateTime.MaxValue是23:59:59.9999999,1999年12月31日

 DateTime dt = new DateTime(1970,1,1,0,0,0,0, DateTimeKind.Utc); Console.Write(dt.AddSeconds(1332958778172D)); 

除了那个…

1332958778172/60/60/24/365 = 42,267年……哪个日期时间最长只能达到23:59:59.9999999,1999年12月31日

我有一个类似的问题,我需要在日期时间添加一个可配置的时间跨度。 如果配置不正确,我必须假设“最糟糕的情况”:MaxValue。

我通过实现DateTime的扩展(仍处于测试阶段)解决了这个问题:

  ///  /// Removes a timespan from a date, returning MinValue or MaxValue instead of throwing exception when if the resulting date /// is behind the Min/Max values ///  ///  public static DateTime SafeAdd(this DateTime source, TimeSpan value) { // Add or remove ? if (value.Ticks > 0) { // add var maxTicksToAdd = DateTime.MaxValue - source; if (value.Ticks > maxTicksToAdd.Ticks) return DateTime.MaxValue; } else { var maxTicksToRemove = source - DateTime.MinValue; // get the value to remove in unsigned representation. // negating MinValues is impossible because it would result in a value bigger than MaxValue : (-32768 .. 0 .. 32767) var absValue = value == TimeSpan.MinValue ? TimeSpan.MaxValue : -value; if (absValue.Ticks > maxTicksToRemove.Ticks) return DateTime.MinValue; } return source + value; }