简体   繁体   中英

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

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?

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM