开发者

Need help with C# ParseExact syntax and moving between timezones

开发者 https://www.devze.com 2023-02-28 04:08 出处:网络
Okay, I have decided to let the magic of Stackoverflow work for me! I have a date in the format: \"Apr 18 2011 19:30 EDT\" that I need开发者_JS百科 to push into a DateTime object in C#. One caviat,

Okay, I have decided to let the magic of Stackoverflow work for me!

I have a date in the format: "Apr 18 2011 19:30 EDT" that I need开发者_JS百科 to push into a DateTime object in C#. One caviat, I also want to shift it to UTC too. Obivisouly when DST is over it'll come over as EST.

I know that I need a statement like:

 DateTime.ParseExact("Apr 18 2011 19:30 EDT",  "MMM DD yyyy something something ",  CultureInfo.InvariantCulture,  DateTimeStyles.None, out convertedDate);

But getting it over to UTC is above my knowlwedge level.

So in summary, I need:

  1. To turn Apr 18 2011 19:30 EDT into a DateTime
  2. Convert the EDT timezone to UTC time.
  3. End up with a DateTime object.

What's the code, wizards?


Well, if it's always going to be in Eastern Daylight Time, you can do something like:

// Parse string. We don't need escaping since E,D and T 
// are not considered special characters by ParseExact.
var dateTimeInEasternTime = DateTime.ParseExact("Apr 18 2011 19:30 EDT",
                                                "MMM dd yyyy HH:mm EDT",    
                                                CultureInfo.InvariantCulture);

// Convert from the relevant timezone to UTC.
var dateTimeInUTC = TimeZoneInfo.ConvertTime
                    (dateTimeInEasternTime,  
                     TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"), 
                     TimeZoneInfo.Utc);

You can cache the TimeZoneInfo representing EST (which becomes EDT while daylight savings is on) to prevent the lookup.

If the string could end with a three letter code representing some arbitrary time-zone, it's going to be a lot more difficult since there are many conventions for them, none of which (AFAIK) are currently supported by .NET. Your best bet would be to first build a lookup from the code to the relevant TimeZoneInfo (perhaps through the Id property) after which you can do the conversion with TimeZoneInfo.ConvertTime as usual.


I'm not sure exactly where you're getting hung up. It sounds like you have successfully parsed the string into a DateTime.

To convert the value to UTC, call the ToUniversalTime() method. Note that this will assume the current time value is relative to your system's current time zone.

ToUniversalTime() converts to a DateTime value.

0

精彩评论

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