15

This is question is not a duplicate, this quesitons demonstrates a problem with a method of conversion, not how to perform the conversion. Read the question in full.

I have a timestamp which I believe is a unix time stamp, when using the following converter it correctly converts the stamp

Value: 1365151714493

http://www.epochconverter.com/

I have looked around and found an example on how to convert this to a datetime obect and the method seems simple, create a datetime object and set the date to the might night on 1/1/1970 and add the value as second:

public static DateTime? ConvertUnixTimeStamp(string unixTimeStamp)
{
    return new DateTime(1970, 1, 1, 0, 0).AddSeconds(Convert.ToDouble(unixTimeStamp));
}

The problem is everytime I call this mehod with the value above I get a value out of range exception.

Do I need to do anything with the value first? the string converts to a double ok. the exception is thrown when calling the AddSeconds(double) methos

Andy Clark
  • 3,363
  • 7
  • 27
  • 42
  • Pretty sure that time-stamp is in milliseconds, _not_ seconds. EDIT: Unless... you know... it's supposed to represent a date 43,259 _years_ in the future. – Chris Sinclair Apr 10 '13 at 12:51
  • How is this a duplicate???? the link you provided is asking how to do the conversion. I am asking about a problem when trying to do the conversion! – Andy Clark Apr 10 '13 at 13:06

2 Answers2

23

That timestamp (1365151714493) is in milliseconds, not seconds. You'll need to divide by 1000 or use AddMilliseconds instead. If it's treated as seconds, it's a date some 43,259 (rough calculation) years in the future. This is beyond the range of DateTime which maxes out at the year 10000, thus throwing the ArgumentOutOfRangeException.

public static DateTime? ConvertUnixTimeStamp(string unixTimeStamp)
{
    return new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(Convert.ToDouble(unixTimeStamp));
}

You may also want to consider forcing it to GMT as V4Vendetta suggested. In addition, if you expect to have a mix of formats (seconds OR milliseconds) perhaps a quick size check on the parsed value might be prudent.

Chris Sinclair
  • 22,858
  • 3
  • 52
  • 93
  • Completely overlooked the possibility of the value being milliseconds, since every article I read gave examples of the time stamp being in seconds I assumed the value given to me was the same. Thanks – Andy Clark Apr 10 '13 at 13:08
6

I guess you should try it as since it is with respect to GMT

Also from the site you mention it assumes that the value is in milliseconds and not the traditional unix timestamp as in seconds

DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
epoch = epoch.AddMilliseconds(yourvalue);// your case results to 4/5/2013 8:48:34 AM
V4Vendetta
  • 37,194
  • 9
  • 78
  • 82