开发者

Converting UK times (both BST and GMT) represented as strings to UTC (in C#)

开发者 https://www.devze.com 2022-12-08 21:23 出处:网络
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 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 ParseUkTi开发者_Go百科meAsUtcTime(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?


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));


How about:

DateTime.Parse(dateTimeString).ToUniversalTime();

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

0

精彩评论

暂无评论...
验证码 换一张
取 消