Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse this DateTime without losing TZ info?

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?

like image 917
spender Avatar asked Sep 01 '25 22:09

spender


2 Answers

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
like image 82
Brad Christie Avatar answered Sep 03 '25 13:09

Brad Christie


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);
}
like image 22
user7116 Avatar answered Sep 03 '25 15:09

user7116