Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# convert UTC int to DateTime object

I don't know why this is so complicated!

I have a plugin that is passing in a long int UTC. I need to convert that number into a DateTime to query my database (SQL Server).

I don't know why, but I can't find a workable answer from a basic google search.

(For extra credit, I need to turn my returned DateTime back into a UTC at the end of the day.)

This is embarrassing to have to ask such a basic question! :)

like image 479
Matt H. Avatar asked Jul 03 '11 19:07

Matt H.


1 Answers

My guess is it's going to be either milliseconds or seconds since a particular epoch - quite possibly the Unix epoch of January 1st 1970, midnight UTC.

So the code would look something like:

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

public static DateTime FromMillisecondsSinceUnixEpoch(long milliseconds)
{
    return UnixEpoch.AddMilliseconds(milliseconds);
}

Make the obvious changes for seconds, or from a different epoch :)

An alternative approach is to create a TimeSpan of the seconds/milliseconds since the epoch, and then add it to the epoch:

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

public static DateTime FromMillisecondsSinceUnixEpoch(long milliseconds)
{
    return UnixEpoch + TimeSpan.FromMilliseconds(milliseconds);
}

I don't know of any significant difference between them - although the fact that AddMilliseconds takes a double instead of a long suggests that for very large values, the TimeSpan approach may be preferable. I doubt that it'll make any difference though :)

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

Jon Skeet