[英]How to convert string to datetime(datetime) in same format?
在這里,我想使用tostring
將日期轉換為字符串,但是當我將其轉換回(從string轉換為datetime)時,格式是不同的。
static void Main(string[] args)
{
string cc = "2014/12/2";
DateTime dt = DateTime.Parse(cc);
Console.WriteLine(dt);
Console.ReadLine();
}
預期輸出:2014/12/2但我得到:2014/12/2
將DateTime
實例轉換回string
時,使用提供的格式調用ToString
:
Console.WriteLine(dt.ToString(@"yyyy/M/d");
string DateString = "06/20/1990";
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime dateVal = DateTime.ParseExact(DateString, "yyyy-MM-dd", culture);
這將是您的願望輸出
過分的
string DateString = "20/06/1990";;
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime dt = DateTime.ParseExact(DateString,"dd/mm/yyyy",culture);
dt.ToString("yyyy-MM-dd");
嘗試這個
DateTime dt = DateTime.ParseExact(dateString, "ddMMyyyy",
CultureInfo.InvariantCulture);
dt.ToString("yyyyMMdd");
用這個:
string cc = "2014/12/2";
DateTime dt = DateTime.Parse(cc);
string str = dt.ToString("yyyy/M/dd"); // 2014/12/02 as you wanted
Console.WriteLine(str);
Console.ReadLine();
您可以使用
string formattedDate= dt.ToString("yyyy/M/d");
對於反向,您可以使用
DateTime newDate = DateTime.ParseExact("2014/05/22", "yyyy/M/d", null);
因此,如果您的預期輸出是:2014/12/2,則必須使用
newDate.ToString(“ yyyy / M / d”);
如您在這里所讀, DateTime.ToString()
使用CurrentCulture
決定如何格式化其輸出( CultureInfo
類型的CurrentCulture
提供有關如何格式化日期,貨幣,日歷等的信息。在C ++中稱為語言環境 )。
因此,前面的答案所建議的最簡單的解決方案是使用ToString()
的重載,該重載接受格式字符串,從而有效地覆蓋CurrentCulture
信息:
dt.ToString(@"yyyy/MM/dd");
有關日期時間格式的更多信息,請參見此處 。
這很簡單,您只需要在顯示期間使用日期模式
string cc = "2014/12/2";
string datePatt = @"yyyy/MM/d";
DateTime dt = Convert.ToDateTime(cc);
Console.WriteLine(dt.ToString(datePatt));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.