Boardy
Boardy

Reputation: 36225

Getting the date and time from epoch taking in Daylight Saving into consideration

I am currently working on a c# application and am using an epoch time stamp and converting it back into a normal date and time. This is pretty much working except at the moment it is returning the time as 1 hour behind as it is not taking the daylight saving into account. How can I find out if the user is in a timezone with daylight saving and correct the time as required.

Thanks for any help you can provide.

Upvotes: 0

Views: 1074

Answers (1)

Martin Liversage
Martin Liversage

Reputation: 106826

You haven't specified how you convert from an epoch time stamp to a DateTime but the epoch time stamp is the number of seconds elapsed since 1970-01-01 00:00:00 UTC so I assume you have a UTC DateTime. You can convert this into a local time stamp taking daylight savings into account using this code:

var date = DateTime.UtcNow; // Should be created from epoch time stamp.
var localDate = date.ToLocalTime();

It is important that the Kind of the DateTime isn't Local. If that is not the case you can modify it yourself:

var date = DateTime.Now; // Should be created from epoch time stamp.
date = DateTime.SpecifyKind(date, DateTimeKind.Utc);
var localDate = date.ToLocalTime();

On Windows the conversion is based on the timezone and daylight savings settings of the current user executing the code.

Upvotes: 4

Related Questions