Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to convert string (yyyyMMddhhmm) into DateTime in C#

In my database I have a field date of type varchar where the date is stored in the following format yyyyMMddhhmm, with no spaces or other characters separating them.

Now I need to compare this date with a C# DateTime, therefore I need to convert the string into DateTime. The most logical way that I can think of is to extract from the variable date the sub-string related to year, month and day and create a new DateTime object:

var year = Convert.ToInt32(date.Substring(0, 4));

var month = Convert.ToInt32(date.Substring(4, 2));

var day = Convert.ToInt32(date.Substring(6, 2));

DateTime dateToCompare = new DateTime(year, month, day);

Is there any available C# method that allows me to perform this conversion without writing all this code?

like image 437
CiccioMiami Avatar asked Dec 02 '22 23:12

CiccioMiami


2 Answers

Absolutely - use DateTime.ParseExact:

DateTime parsed = DateTime.ParseExact(text, "yyyyMMddHHmm",
                                      CultureInfo.InvariantCulture);

Note the HH for 24-hour instead of hh for 12-hour format.

Alternatively, you could use DateTime.TryParseExact, which returns a true/false value to indicate whether or not the parsing was successful. If you're fully expecting all the data to be valid, and it's reasonable for an exception to be thrown otherwise, then DateTime.ParseExact is fine.

As a very different alternative, you could use Noda Time:

// Do this once...
var pattern = LocalDateTimePattern.CreateWithInvariantInfo("yyyyMMddHHmm");

// Do this repeatedly...
var parseResult = pattern.Parse(text);
if (parseResult.Success)
{
    LocalDateTime value = parseResult.Value;
    // Use the value...
}
else
{
    // Error... 
}

Or for the "just throw an exception" behaviour, just use parseResult.Value unconditionally.

EDIT: As an aside, is there any reason why you're storing dates in a varchar column? Can you fix your schema instead?

like image 145
Jon Skeet Avatar answered Dec 24 '22 02:12

Jon Skeet


You can use DateTime.ParseExact method.

like image 24
Felice Pollano Avatar answered Dec 24 '22 01:12

Felice Pollano