Bob Bob - 3 months ago 18
C# Question

c# DataTime: Assume EST convert to GTM

I have a server running in New York that saves a DateTime into the database in local time.

I then have a client application running in GMT timezone that needs to save down a DateTime in the same local New York time
Can I do using:

TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"))


Or I need to consider daylight savings?

Now in my UI I need to display 2 columns. 1) the DateTime from the database and the DateTime in the database converted to GMT

How can I do this?

Answer

The TimeZoneInfo class should give you what you need.

var date = (DateTime)reader[0]; // Retrieve data from database however you normally get it

var est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
var utcTime = TimeZoneInfo.ConvertTimeToUtc(date, est);

var localTime = utcTime.ToLocalTime();

Edit: You modified your question to indicate you have looked at TimeZoneInfo, so this doesn't add much anymore. However to resolve the ambiguous time issue mentioned by Jon, take a look at the IsAmbiguousTime() and GetAmbiguousTimeOffsets() methods to be able to detect values that can't be definitively converted.

Comments