I have a string in the following format yyyyMMdd and I am trying to get it to look like this:
yyyy-MM-dd
When I try:
string date = "20121004";
Convert.ToDateTime(date).ToString("yyyy-MM-dd");
I get the error:
FormatException: String was not recognized as a valid DateTime.
Would the following work or would I run into a problem:
private string GetValidDate(string date,string format)
{
DateTime result;
if(DateTime.TryParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
{
return date;
}
else if(DateTime.TryParseExact(date, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
{
return DateTime.ParseExact(date, "yyyyMMdd",
CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
}
else
{
return "Invalid Date Format";
}
}
Just use the
DateTime.ParseExactmethod:This also provides the advantage of validating the date before reformatting it with the hyphens.
ParseExactthrows an exception you can catch, if the date is not in valid range, or the format does not match.