tags:

views:

272

answers:

4

I have the following date stored as a string

  04.09.2009 (dd.mm.yyyy)

Now I would like it changed to this format:

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

Remember output should be a string value and the input date is a string.

What is the best way to convert it with minimal effort?

+5  A: 

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 for the culture to use the culture of the current thread.)

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));
    }
}
Jon Skeet
+3  A: 
DateTime dateTime = DateTime.ParseExact("04.09.2009", "dd.MM.yy", null);
dateTime.ToString("yyyy/MM/dd");
Elisha
+1  A: 

Why are you storing the date as a string? That's generally a bad idea...

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

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

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

Guffa
+1  A: 

If your input and output are both strings then you're not really dealing with dates at all. You can just 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);
LukeH