我不知道为什么会这么复杂!
I don't know why this is so complicated!
我有一个插件,它是传递一个长整型UTC。我需要这个数字转换成的DateTime
来查询我的数据库(SQL Server)。
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.
(对于额外的学分,我需要把我的返回的DateTime
返回到一个UTC在这一天结束。)
(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! :)
我的猜测是,这将是无论是毫秒或秒,因为一个特殊的时期 - 1970年1月1日,午夜(UTC)的很可能是Unix纪元
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.
所以,code看起来是这样的:
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);
}
我不知道它们之间的任何显著差异 - 尽管事实上, AddMilliseconds
需要双
而不是的长
表明,对于非常大的数值,在时间跨度
办法可能是preferable。我怀疑它会让任何区别,但:)
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 :)