Gary
Gary

Reputation: 1774

Converting ticks to 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?

Upvotes: 6

Views: 20165

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292445

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);
}

Upvotes: 20

Related Questions