Popular Posts

Friday, January 21, 2011

Parsing DateTime strings

Here is how to parse a date that is in the format of mm/dd/yyyy:


// Parse string with date but no time component.

string dateString, format;
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;

// Parse date-only value with invariant culture.
dateString = "06/15/2008";
format = "d";
try
{
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
Console.WriteLine("{0} is not in the correct format.", dateString);
}

No comments: