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?
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?
You can use DateTime.ParseExact method.
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