如何从unix时代转换为C#中的夏令时? [英] How do I convert from unix epoch time and account for daylight saving time in C#?
问题描述
我有一个从unix时代转换为.NET DateTime值的函数:
I have a function that converts from unix epoch time to a .NET DateTime value:
public static DateTime FromUnixEpochTime(double unixTime )
{
DateTime d = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return d.AddSeconds(unixTime);
}
我在哪里(英国)夏天时间前进一小时。
Where I am (UK) the clocks go one hour forward for summer time.
在Python中,我使用 time.time()
(并为了参数,现在的时间是17:15:00),这给我一个值 1286122500
。
In Python I get the local Epoch time using time.time()
(and for the sake of argument, right now the time is 17:15:00) which gives me a value of 1286122500
.
如果我转换这回到人的可读时间,使用 time.localtime()
它会按照我的预期转换回17:15。
If I convert this back to a human readable time using time.localtime()
it converts back to 17:15 as I would expect.
如何将unix纪元时间转换回.NET DateTime
值和本地夏令时的帐户。我的上述功能将 1286122500
转换为16:15,这对我的地理位置不正确。
How do I convert unix epoch time back to a .NET DateTime
value AND account for local daylight savings time. My function above converts 1286122500
back to 16:15 which is incorrect for my geographic location.
推荐答案
使用 DateTime.ToLocalTime()
:
http://msdn.microsoft.com/en-us/library/system.datetime.tolocaltime.aspx
public static DateTime FromUnixEpochTime(double unixTime)
{
DateTime d = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
d = d.AddSeconds(unixTime);
return d.ToLocalTime();
}
这篇关于如何从unix时代转换为C#中的夏令时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!