Adding Seconds to DateTime with a Valid Double Results in ArgumentOutOfRangeException

前端 未结 7 1231

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.

提交回复
热议问题