Parsing non standard date strings in C#

535 Views Asked by At

How would you handle the following string value that needs to be converted to a DateTime object?

"2015/01/22 12:08:51 (GMT+09:00)"

Would like to include this as a recognized DateTime pattern. As I encounter other formats, I would like to just implement a new pattern.

4

There are 4 best solutions below

1
On

Using DateTime.ParseExact is probably your best bet. It takes in an input string and an expected format string that the input should match. It will return true if the conversion was successful, and the out parameter will be the result of the conversion (result in the example below).

I was unable to get it to work without forcibly removing the "GMT" portion, but if that's acceptable to you, the code below should work.

This example takes the original input and converts it to UTC time (i.e. it adjusts the time based on your GMT value, which is to subtract 9 hours in your example):

var input = "2015/01/22 12:08:51 (GMT-08:00)";
var format = "yyyy/MM/dd H:mm:ss (zzz)";

DateTime result;

// Remove the "GMT" portion of the input
input = input.Replace("GMT", "");

if (DateTime.TryParseExact(input, format, CultureInfo.InvariantCulture,
    DateTimeStyles.AdjustToUniversal, out result))
{
    Console.WriteLine($"'{input}' converts to {result} UTC time.");
}
else
{
    Console.WriteLine($"'{input}' is not in the correct format.");
}

This example is modified from the ones on the DateTime.TryParseExact documentation.

1
On

Here a piece of code that will successfully parse the given string (notice DateTimeOffset rather than DateTime):

var str = "2015/01/22 12:08:51 (GMT+09:00)";

var dt = DateTimeOffset.ParseExact
    (str,
    "yyyy/MM/dd HH:mm:ss (\\G\\M\\TK)",
    System.Globalization.CultureInfo.InvariantCulture
    );
//dt now has +9:00 offset - that's correct only if GMT is provided as UTC.

More info at The Difference Between GMT and UTC

0
On

This code takes a string and converts it into a DateTime object

DateTime myDate = DateTime.Parse("2017-08-28 14:20:52,001", "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture);

All you need to do is create a format that matches your input. This link helps: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

For more details read this: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/how-to-convert-a-string-to-a-datetime

0
On

Here there is the official documentation of DateTime.Parse with some examples. It covers also the case of other formats https://msdn.microsoft.com/it-it/library/system.datetime.parse(v=vs.110).aspx