Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 20121004 (yyyyMMdd) to a valid date time?

Tags:

c#

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";
     }
}
like image 382
Xaisoft Avatar asked Jun 15 '12 15:06

Xaisoft


People also ask

How do I convert DateTime to date format?

To convert a datetime to a date, you can use the CONVERT() , TRY_CONVERT() , or CAST() function.


4 Answers

Just use the DateTime.ParseExact method:

string date = "20121004";

string result = DateTime.ParseExact(date, "yyyyMMdd",
                CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");

This also provides the advantage of validating the date before reformatting it with the hyphens. ParseExact throws an exception you can catch, if the date is not in valid range, or the format does not match.

like image 88
Philip Daubmeier Avatar answered Oct 15 '22 09:10

Philip Daubmeier


I get the error:

FormatException: String was not recognized as a valid DateTime.

You are getting this error because you are not telling the ToDateTime() method how to figure out to parse your string.

If you use the following method:

public static DateTime ParseExact(
    string s,
    string format,
    IFormatProvider provider,
    DateTimeStyles style
)

You won't get this error. After you generate a DateTime variable just display it in the format yyyy-dd-mm using the ToString() method.

public string ToString(
    string format,
    IFormatProvider provider
)

http://msdn.microsoft.com/en-us/library/8tfzyc64
http://msdn.microsoft.com/en-us/library/9h21f14e

I know this basically repeats the same information as everyone else but it also provides him the ability to understand what the two methods he needs to use actually does.

like image 40
Security Hound Avatar answered Oct 15 '22 11:10

Security Hound


Here is an extension method I use.

/// <summary>
/// Converts a string to a dateTime with the given format and kind.
/// </summary>
/// <param name="dateTimeString">The date time string.</param>
/// <param name="dateTimeFormat">The date time format.</param>
/// <param name="dateTimeKind">Kind of the date time.</param>
/// <returns></returns>
public static DateTime ToDateTime(this string dateTimeString, string dateTimeFormat, DateTimeKind dateTimeKind)
{
    if (string.IsNullOrEmpty(dateTimeString))
    {
        return DateTime.MinValue;
    }

    DateTime dateTime;
    try
    {
        dateTime = DateTime.SpecifyKind(DateTime.ParseExact(dateTimeString, dateTimeFormat, CultureInfo.InvariantCulture), dateTimeKind);
    }
    catch (FormatException)
    {
        dateTime = DateTime.MinValue;
    }

    return dateTime;
}
like image 21
Tim Sullivan Avatar answered Oct 15 '22 11:10

Tim Sullivan


It's a little ugly, but how about this?

date.Insert(6, "-").Insert(4, "-");

If you can assume you're coming in with a string representing a valid date and you don't need to do any other date-ish logic, then why go to a DateTime in the first place?

like image 42
James Cronen Avatar answered Oct 15 '22 11:10

James Cronen