我作爲字符串存儲C#將字符串日期格式轉換爲另一個字符串的最佳方法?
04.09.2009 (dd.mm.yyyy)
現在我想將其改爲這種格式在以下日期:
2009/08/31 (yyyy/mm/dd)
記住輸出應該是一個字符串值,輸入日期爲一個字符串。
什麼是最小的努力來轉換它的最佳方式是什麼?
我作爲字符串存儲C#將字符串日期格式轉換爲另一個字符串的最佳方法?
04.09.2009 (dd.mm.yyyy)
現在我想將其改爲這種格式在以下日期:
2009/08/31 (yyyy/mm/dd)
記住輸出應該是一個字符串值,輸入日期爲一個字符串。
什麼是最小的努力來轉換它的最佳方式是什麼?
爲什麼你是否將日期存儲爲字符串?這通常是一個糟糕的主意......
要轉換你解析成一個日期時間值的字符串,轉換成字符串格式:
string newFormat = DateTime.ParseExact(theDate, "dd'.'MM'.'yyyy", CultureInfo.InvariantCulture).ToString("yyyy'/'MM'/'dd")
(請注意,您需要周圍的斜線撇號,以獲得字面字符,否則它將使用文化的日期分隔符,可能是不同的字符。)
喜歡的東西:
public static string ConvertDateTimeFormat(string input, string inputFormat,
string outputFormat, IFormatProvider culture)
{
DateTime dateTime = DateTime.ParseExact(input, inputFormat, culture);
return dateTime.ToString(outputFormat, culture);
}
(您可以爲文化使用當前線程的文明指定null
)
測試代碼:
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));
}
}
DateTime dateTime = DateTime.ParseExact("04.09.2009", "dd.MM.yy", null);
dateTime.ToString("yyyy/MM/dd");
如果你的輸入和輸出都是字符串,那麼你根本就沒有處理日期。你可以使用字符串操作來執行轉換:
string original = "04.09.2009";
string converted = original.Substring(6, 4) + "/" +
original.Substring(3, 2) + "/" +
original.Substring(0, 2);
工作就像一個魅力 –
VAR日期= 「&DateFrom =」 +(txt_dateF.Text == 「」 「?」:DateTime.ParseExact(txt_dateF.Text, 「dd/MM/yyyy」,CultureInfo.InvariantCulture).ToString(「yyyy/MM/dd」)); –