tags:

views:

787

answers:

2

I have to use some dates and times from a legacy database. They are represented as strings. Dates are dd/MM/yy. Times are HH:mm.

I'd like to convert these to UTC as soon as I pull them from the database. I'm working on US systems, so need a common time.

The problem I'm facing is how to convert them to UTC DateTime values. I can do the parsing, etc. The real problem I have concerns the timezone.

I'm trying to use the following approach:

DateTime ukTime = // Parse the strings in a DateTime value.
TimeZoneInfo timeZoneInformation = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
DateTimeOffset utcTime = new DateTimeOffset(ukTime, timeZoneInformation.BaseUtcOffset);

However, this gives incorrect values if the date is in the British Summer Time period.

I can use "GMT Daylight Time" on those dates, but that requires me to know when the switchover is. I'm sure there must be a less laborious way.

As I'm not using a machine with UK time settings I can't rely on local time.

Basically, I need something like:

// Works for both GMT (UTC+0) and BST (UTC+1) regardless of the regional settings of the system it runs on.
DateTime ParseUkTimeAsUtcTime(string date, string time)
{
    ...
}

I've scoured the posts, but couldn't find anything that addressed this directly. Surely this is also an issue with EST, EDT, etc?

A: 

Try using the GetUtcOffset() method on your TimeZoneInfo instance, which takes "adjustment rules" into consideration.

Using this should work basically the same as your original example, but you'll use that method instead of the BaseUtcOffset property.

DateTime ukTime = // Parse the strings in a DateTime value.
TimeZoneInfo timeZoneInformation = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
DateTimeOffset utcTime = new DateTimeOffset(ukTime, timeZoneInformation.GetUtcOffset(ukTime));
bdukes
Nice, but could you maybe post a code sample for the ignorant? This should be a canonical resource.
John Gietzen
I think this example should cover what you need to do. Let me know if you've simplified this at all.
bdukes
A: 

How about:

DateTime.Parse(dateTimeString).ToUniversalTime();

Assuming that the database server stores its datetimes in the same timezone as your application server.

Andy J