Created
September 8, 2015 21:49
-
-
Save f1code/1a05c1a70d3e6dab31f4 to your computer and use it in GitHub Desktop.
DateTimeParser with Timezone string conversion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public static class DateTimeParser | |
| { | |
| private static readonly Dictionary<string, string> TimeZones = new Dictionary<string, string>() | |
| { | |
| {"CDT", "-0500"}, | |
| {"CST", "-0600"}, | |
| {"EDT", "-0400"}, | |
| {"EST", "-0500"}, | |
| {"PDT", "-0700"}, | |
| {"PST", "-0800"}, | |
| {"MST", "-0700"}, | |
| {"MDT", "-0600"}, | |
| }; | |
| /// <summary> | |
| /// Parse a date string containing a timezone description (e.g. 01/22/2015 07:13 PM EST) | |
| /// Only common US timezones are supported. | |
| /// </summary> | |
| /// <param name="callDate"></param> | |
| /// <returns></returns> | |
| public static DateTimeOffset? ParseDateWithTimezone(string callDate) | |
| { | |
| DateTimeOffset result; | |
| callDate = TimeZones.Aggregate(callDate, (current, kvp) => current.Replace(kvp.Key, kvp.Value)); | |
| if (DateTimeOffset.TryParse(callDate, out result)) | |
| return result; | |
| return null; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| [TestFixture] | |
| public class TestDateTimeParser | |
| { | |
| [Test] | |
| public void ParseValidDate() | |
| { | |
| var valid = "01/22/2015 07:13 PM EST"; | |
| var result = DateTimeParser.ParseDateWithTimezone(valid); | |
| Assert.IsNotNull(result); | |
| Assert.AreEqual(2015, result.Value.UtcDateTime.Year); | |
| Assert.AreEqual(1, result.Value.UtcDateTime.Month); | |
| Assert.AreEqual(23, result.Value.UtcDateTime.Day); | |
| Assert.AreEqual(0, result.Value.UtcDateTime.Hour); | |
| Assert.AreEqual(13, result.Value.UtcDateTime.Minute); | |
| Assert.AreEqual(0, result.Value.UtcDateTime.Second); | |
| } | |
| [Test] | |
| public void ParseInvalidDateShouldReturnNull() | |
| { | |
| var invalid = "01/22/2015 07:13 PM CEDT"; | |
| var result = DateTimeParser.ParseDateWithTimezone(invalid); | |
| Assert.IsNull(result); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment