I have a bunch of strings that are DateTime values dumped from some database... Probably MySql. I have no control on the structure.
The strings look like this:
2011-05-17 00:00:00 Etc/GMT
I've found solutions that involve replacing "Etc/GMT" prior to the parse. This smells bad.
Is there a one step solution to turning this string to a DateTime without stripping out the timezone info?
DateTime.ParseExact
Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
For funky formats you can use ParseExact
. And you also probably want to use DateTimeStyles.AssumeUniversal
:
String original = "2011-05-17 00:00:00 Etc/GMT";
DateTime result = DateTime.ParseExact(
original,
"yyyy-MM-dd HH:mm:ss 'Etc/GMT'",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AssumeUniversal);
Console.WriteLine(result.ToString()); // given my timezone: 5/16/2011 8:00:00 PM
Console.WriteLine(result.ToUniversalTime().ToString()); // 5/17/2011 12:00:00 AM
It appears that Noda Time contains Etc/GMT
in its time zone database based on a quick look at the source.
The means by which you parse dates and times is a bit different in Noda Time than in the .Net Framework (I'm by no means an expert in Noda Time):
var pattern = ZonedDateTimePattern.CreateWithInvariantCulture(
@"yyyy'-'MM'-'dd HH':'mm':'ss z",
DateTimeZoneProviders.Tzdb);
var result = pattern.Parse(@"2011-05-17 00:00:00 Etc/GMT");
if (result.Success)
{
Console.WriteLine("{0}", result.Value);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With