How do I convert from unix epoch time and account for daylight saving time in C#?

只谈情不闲聊 提交于 2019-12-23 07:13:09

问题


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.

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.

If I convert this back to a human readable time using time.localtime() it converts back to 17:15 as I would expect.

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.


回答1:


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



回答2:


The TimeZoneInfo class is great at helping one deal with different times and time zones. It uses the time zone information that Windows has built in to convert between different time zones.

Here's how you'd use it for your problem:

//Get your unix epoch time into a DateTime object
DateTime unixTime = 
    new DateTime(1970,1,1,0,0,0, DateTimeKind.Utc).AddSeconds(1286122500);

//Convert to local time
DateTime localTime = TimeZoneInfo.ConvertTime(unixTime, TimeZoneInfo.Local);

TimeZoneInfo.Local returns the TimeZoneInfo that represents the local time zone.




回答3:


Is your daylight savings about to end? If so, your timezone files may be out of date, thinking it's already ended. (I don't know about the UK, but in the US, the scope of daylight savings was expanded 3 years ago, and many installations still don't have the updated data.)

In short, make sure your timezone data is up to date. :-)




回答4:


It's 17:15 for 1286122500 in the BST (or GMT+1) timezone (British Summer Time).

Your function uses DateTimeKind.Utc which tells it to use UTC (aka GMT), so you get a time in GMT: 16:15. In addition, I don't think changing the time zone of the unix epoch reference will necessary affect your current local timezone correctly.

Instead, you could try something like this:

DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime d = unixEpoch + new TimeSpan(unixTime);

(and then convert to DateTimeKind.Local)



来源:https://stackoverflow.com/questions/3850605/how-do-i-convert-from-unix-epoch-time-and-account-for-daylight-saving-time-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!