8

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?

4 Answers 4

12

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

var date = "&DateFrom=" + (txt_dateF.Text == "" ? "" : DateTime.ParseExact(txt_dateF.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy/MM/dd"));
9

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));
    }
}

Comments

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

Comments

3

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.