6

There are a number of questions on this site explaining how to do this. My problem I when I do what seems to work for everyone else I don't get the correct date or time. The code is ...

long numberOfTicks = Convert.ToInt64(callAttribute);
startDateTime = new DateTime(numberOfTicks);

The value of callAttribute is = "1379953111"

After converting it the value of numberOfTicks = 1379953111

But the DateTime ends up being startDateTime = {1/1/0001 12:02:17 AM}

I have taken the same value for ticks and converted it online and it comes up with the correct date/time.

What am I doing wrong?

crthompson
  • 15,653
  • 6
  • 58
  • 80
Gary
  • 1,784
  • 4
  • 18
  • 38
  • What value are you expecting? – Anthony Sep 23 '13 at 16:33
  • possible duplicate of [How to convert UNIX timestamp to DateTime and vice versa?](http://stackoverflow.com/questions/249760/how-to-convert-unix-timestamp-to-datetime-and-vice-versa) – Dustin Kingen Sep 23 '13 at 16:34
  • It is the number of ticks and it has nothing to do with seconds. The date/time I'm expecting is 9/23/2013 09:18:31. If I enter the number into Epoch Converter I receive the correct date/time back. – Gary Sep 23 '13 at 16:42
  • 1
    What leads you to believe that it's ticks? I think it would be a *fantastic* coincidence for treating that value as the common "number of seconds since the Unix epoch" to give the right value, but for it to be actually a number of ticks. – Jon Skeet Sep 23 '13 at 16:46
  • @Gary: Epoch Converter uses seconds since the unix epoch or milliseconds since the unix epoch. – Jon Skeet Sep 23 '13 at 16:46
  • Thanks, I thought it was using ticks. – Gary Sep 23 '13 at 16:49

1 Answers1

20

Your value doesn't seem to be a number of ticks; I suspect it's a UNIX timestamp (number of seconds since 1970/01/01 UTC)

Here's a function to convert from a UNIX timestamp:

static readonly DateTime _unixEpoch =
    new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

public static DateTime DateFromTimestamp(long timestamp)
{
    return _unixEpoch.AddSeconds(timestamp);
}
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • 2
    To save people from having to check, the question's value of `1379953111` would return `9/23/2013 4:18:31 PM`, which definitely points to this being the right answer assuming the user recently was using a 'DateTime.Now` or the like and he's probably in a different time zone or a couple hours offset one way or another. – Anthony Sep 23 '13 at 16:39
  • 2
    You should specify the "kind" of the Unix epoch as Utc, given that that is how the Unix epoch is defined. – Jon Skeet Sep 23 '13 at 16:39