Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 841
Kev Avatar asked Oct 03 '10 16:10

Kev


People also ask

Does Unix time account for daylight savings?

The unix timestamp does not contain any timezone data. It is UTC and has no DST settings.

How does Epoch time work with Daylight Savings Time?

The milliseconds since epoch are not influenced by timezones and daylight saving time (daylight saving time just changed the timezone with -1 / +1). The milliseconds/seconds since epoch are (always?) in UTC (or GMT + 0). Yes - It is always based on UTC, excluding leap seconds.

How do I convert epoch time to readable time?

Convert from epoch to human-readable datemyString := DateTimeToStr(UnixToDateTime(Epoch)); Where Epoch is a signed integer. Replace 1526357743 with epoch. =(A1 / 86400) + 25569 Format the result cell for date/time, the result will be in GMT time (A1 is the cell with the epoch number).


2 Answers

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();
}
like image 163
Dan Dumitru Avatar answered Oct 21 '22 19:10

Dan Dumitru


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.

like image 24
Daniel Chambers Avatar answered Oct 21 '22 19:10

Daniel Chambers