C # Best way to convert date string format to another string?
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 to share
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 to share
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 to share