Adding Seconds to DateTime with a Valid Double Results in ArgumentOutOfRangeException

前端 未结 7 1229

The following code crashes and burns and I don\'t understand why:

DateTime dt = new DateTime(1970,1,1,0,0,0,0, DateTimeKind.Utc);
double d = double.Parse(\"1         


        
相关标签:
7条回答
  • 2021-01-17 10:40

    As others have said, the problem is that the value is too large.

    Having looked over it, I believe it represents milliseconds since the Unix epoch, not seconds so you want:

    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));
    

    Either that, or divide by 1000 before calling AddSeconds - but obviously that will lose data.

    0 讨论(0)
  • 2021-01-17 10:42

    The value you are adding results in a date outside of the valid range of dates that a DateTime supports.

    DateTime supports 01/01/0001 00:00:00 to 31/12/9999 23:59:59.

    A simple calculation of 1332958778172/3600/24/365 gives 42267 years.

    0 讨论(0)
  • 2021-01-17 10:44

    I think the double value is genuinely too large. It represents just over 42,267 years (if my maths is correct), and DateTime.MaxValue is 23:59:59.9999999, December 31, 9999

    0 讨论(0)
  • 2021-01-17 10:45

    Looks like this timestamp is in milliseconds, try below code it should work fine.

    DateTime nDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    double epoch = 1585008000000;
    DateTime rDate = nDateTime.AddMilliseconds(epoch);
    
    0 讨论(0)
  • 2021-01-17 10:54

    In my case I had to consume an api object as a double and convert the unix time to a DateTime:

    DateTime Date = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(Double.Parse("1596225600000"));
    
    0 讨论(0)
  • 2021-01-17 10:58
    DateTime dt = new DateTime(1970,1,1,0,0,0,0, DateTimeKind.Utc);    
    Console.Write(dt.AddSeconds(1332958778172D));
    

    Except that...

    1332958778172/60/60/24/365 = 42,267 years... which DateTime can only go up to 23:59:59.9999999, December 31, 9999

    0 讨论(0)
提交回复
热议问题