Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Seconds to DateTime with a Valid Double Results in ArgumentOutOfRangeException

Tags:

c#

.net

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("1332958778172");

Console.Write(dt.AddSeconds(d));

Can someone tell me what's going on? I just can't seem to be able to figure out why...

EDIT

This value comes back from the Salesforce REST API and from what I understand it's a Unix epoch time stamp. "The time of token issue, represented as the number of seconds since the Unix epoch (00:00:00 UTC on 1 January 1970)."

SOLUTION

Salesforce REST API is in fact sending milliseconds back for the issued_at field when performing the OAuth request when they say they're sending seconds...

like image 698
Gup3rSuR4c Avatar asked Mar 28 '12 19:03

Gup3rSuR4c


2 Answers

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.

like image 69
Jon Skeet Avatar answered Sep 18 '22 15:09

Jon Skeet


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.

like image 36
Phil Avatar answered Sep 18 '22 15:09

Phil