Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting ticks to DateTime

Tags:

c#

datetime

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?

like image 746
Gary Avatar asked Sep 23 '13 16:09

Gary


1 Answers

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);
}
like image 176
Thomas Levesque Avatar answered Oct 07 '22 02:10

Thomas Levesque