[c#] How to convert any date format to yyyy-MM-dd

My app parses a string data, extracts the date and identify the format of the date and convert it to yyyy-MM-dd.

The source date could be anything lime dd-mm-yyyy, dd/mm/yyyy, mm-dd-yyyy, mm/dd/yyyy or even yyyy-MM-dd.

Other than attempting different permutations and combinations using switch case, is there any other efficient way to do it?

string sourceDate = "31-08-2012";
String.Format("{0:yyyy-MM-dd}", sourceDate);

The above code simply returns the same sourceDate "31-08-2012".

This question is related to c#

The answer is


You will need to parse the input to a DateTime object and then convert it to any text format you want.

If you are not sure what format you will get, you can restrict the user to a fixed format by using validation or datetimePicker, or some other component.


string sourceDateText = "31-08-2012";
DateTime sourceDate = DateTime.Parse(sourceDateText, "dd-MM-yyyy")
string formatted = sourceDate.ToString("yyyy-MM-dd");

if (DateTime.TryParse(datetoparser, out dateValue))
{
   string formatedDate = dateValue.ToString("yyyy-MM-dd");
}

Try this code:

 lblUDate.Text = DateTime.Parse(ds.Tables[0].Rows[0]["AppMstRealPaidTime"].ToString()).ToString("yyyy-MM-dd");

This is your primary problem:

The source date could be anything like dd-mm-yyyy, dd/mm/yyyy, mm-dd-yyyy, mm/dd/yyyy or even yyyy-MM-dd.

If you're given 01/02/2013, is it Jan 2 or Feb 1? You should solve this problem first and parsing the input will be much easier.

I suggest you take a step back and explore what you are trying to solve in more detail.


You can write your possible date formats in array and parse date as following:

public static void Main(string[] args)
        {
            string dd = "12/31/2015"; //or 31/12/2015
            DateTime startDate;
            string[] formats = { "dd/MM/yyyy", "dd/M/yyyy", "d/M/yyyy", "d/MM/yyyy",
                                "dd/MM/yy", "dd/M/yy", "d/M/yy", "d/MM/yy", "MM/dd/yyyy"};
            
            DateTime.TryParseExact(dd, formats, 
            System.Globalization.CultureInfo.InvariantCulture,
            System.Globalization.DateTimeStyles.None, out startDate);
                
            Console.WriteLine(startDate.ToString("yyyy-MM-dd"));
            
        }

You can change your Date Format From dd/MM/yyyy to yyyy-MM-dd in following way:

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

Here, SourceDate is variable in which you will get selected date.


Convert your string to DateTime and then use DateTime.ToString("yyyy-MM-dd");

DateTime temp = DateTime.ParseExact(sourceDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
string str = temp.ToString("yyyy-MM-dd");