12

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.

4 Answers 4

21

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();
}
1
  • Ah ha...I tried DateTimeKind.Local in the DateTime constructor, can't believe I missed the .ToLocalTime() method.
    – Kev
    Oct 3, 2010 at 17:23
5

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.

1

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

0
1

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.