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.
The unix timestamp does not contain any timezone data. It is UTC and has no DST settings.
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.
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).
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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With