C # Best way to convert date string format to another string?

I have the following date stored as a string

  04.09.2009 (dd.mm.yyyy)

      

Now I would like it to be changed to this format:

  2009/08/31 (yyyy/mm/dd)

      

Remember, the output must be string and the input date must be string.

What's the best way to convert it with minimal effort?

+2


source to share


4 answers


Why are you storing the date as a string? This is generally a bad idea ...

To convert a string, you parse it into a DateTime value, the format that is in the string:



string newFormat = DateTime.ParseExact(theDate, "dd'.'MM'.'yyyy", CultureInfo.InvariantCulture).ToString("yyyy'/'MM'/'dd")

      

(Note that you need apostrophes around the forward slashes to get the literal character, otherwise it will use the culture date separator character, which could be a different character.)

+5


source


Something like:

public static string ConvertDateTimeFormat(string input, string inputFormat,
    string outputFormat, IFormatProvider culture)
{
    DateTime dateTime = DateTime.ParseExact(input, inputFormat, culture);
    return dateTime.ToString(outputFormat, culture);
}

      

(You can specify null

that the culture uses the culture of the current stream.)



Test code:

using System;

class Test
{
    public static string ConvertDateTimeFormat(string input, string inputFormat,
        string outputFormat, IFormatProvider culture)
    {
        DateTime dateTime = DateTime.ParseExact(input, inputFormat, culture);
        return dateTime.ToString(outputFormat, culture);
    }

    static void Main()
    {
        Console.WriteLine(ConvertDateTimeFormat("04.09.2009", "dd'.'MM'.'yyyy",
                                                "yyyy'/'MM'/'dd", null));
    }
}

      

+8


source


DateTime dateTime = DateTime.ParseExact("04.09.2009", "dd.MM.yy", null);
dateTime.ToString("yyyy/MM/dd");

      

+3


source


If your input and output are strings, you are not dealing with dates at all. You can simply use string manipulation to perform the conversion:

string original = "04.09.2009";
string converted = original.Substring(6, 4) + "/" +
                   original.Substring(3, 2) + "/" +
                   original.Substring(0, 2);

      

+1


source







All Articles