字符串的值采用“dd/MM/yyyy”格式,如“04/10/2012”。这应该转换为日期 w.r.t OS 的 Current Culture。
我已经尝试使用 Korean as Current Culture 操作系统的以下字符串,其中日期格式为 yyyy-MM-dd,我的代码没有得到正确的月份值,它将月份值与日期交换:
输入:“04/10/2012” 输出:2012-04-10
代码:
DateTime DT;
string dt = "04/10/2012";
DateTimeFormatInfo DateInfo = CultureInfo.CurrentCulture.DateTimeFormat;
DT = Convert.ToDateTime(String.Format ("{0:"+DateInfo .ShortDatePattern +"}", dt.Trim ()), CultureInfo .CurrentCulture);
MessageBox.Show("Date: " + DT.ToShortDateString());
我该如何解决?
最佳答案
在我看来你需要用固定格式解析它,我认为你目前正在用“dd/MM/yyyy”以外的格式解析它并且因为日期不明确(如月和日可以互换而不会导致无效日期)格式只是切换月份和日期值。当你再去输出它时,它看起来是相反的。
使用DateTime.ParseExact
强制解析格式,然后在DateTime
上使用内置的当前文化敏感字符串输出方法来获取格式化字符串:
var date = DateTime.ParseExact("04/10/2012", "dd/MM/yyyy", CultureInfo.InvariantCulture);
MessageBox.Show("Date: " + date.ToShortDateString()); // Assumes current culture is controlling format
关于c# - 如何将格式为 "dd/MM/yyyy"的日期字符串转换为操作系统当前文化日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12722734/