[英]I have a problem with format a date in C#
我的電腦時間是美國格式 M/dd/yyyy h:mm tt 所以如果我創建一個日期時間,例如 DateTime.Now,它將與我的電腦采用相同的格式,但我需要另一種格式 yyyy/MM/dd HH:mm:ss,但我無法將 DateTime.Now 更改為另一種格式,因為我只能在結果為字符串時執行此操作,但我需要 DateTime 類型的變量。
我試圖像這樣解決這個問題:
string formattedDate = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
var time = DateTime.ParseExact(formattedDate, "yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture);
Console.WriteLine(formattedDate);
Console.WriteLine(time);
但我得到了這個 output: Output
可以為線程指定文化。
System.Globalization.CultureInfo.DefaultThreadCurrentCulture = new System.Globalization.CultureInfo("en-US");
Console.WriteLine(DateTime.Now); // 1/13/2023 5:36:22 PM
System.Globalization.CultureInfo.DefaultThreadCurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
Console.WriteLine(DateTime.Now); // 01/13/2023 17:36:22
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.