C# convert UTC int to DateTime object

非 Y 不嫁゛ 提交于 2019-12-03 13:37:03
Jon Skeet

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 :)

Is the int you get seconds, milliseconds, or what? After converting it to ticks, (one .NET tick is 100 nanoseconds) e.g. by long ticks = theDBDateNum*TimeSpan.TicksPerMillisecond;, try this:

DateTime theDate = new DateTime(ticks, DateTimeKind.Utc);

According to https://www.epochconverter.com/,

The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT), not counting leap seconds.

And later,

var epoch = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;

Later still,

private string epoch2string(int epoch) {
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(epoch).ToShortDateString(); }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!