【问题标题】:How to Convert a Date String with Format "dd/MM/yyyy" to OS Current Culture Date Format如何将格式为“dd/MM/yyyy”的日期字符串转换为 OS 当前文化日期格式
【发布时间】:2012-10-04 07:58:24
【问题描述】:

字符串具有“dd/MM/yyyy”格式的值,例如“04/10/2012”。这应该转换为 OSCurrent 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());

我该如何解决这个问题?

【问题讨论】:

标签: c# winforms visual-studio-2008 datetime


【解决方案1】:

在我看来,您需要使用固定格式解析它,我认为您目前正在使用“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

【讨论】:

    【解决方案2】:

    由于您的输入字符串是固定格式,您应该以该格式对其进行解析:

    DateTime.ParseExact(dt, "dd/MM/yyyy", CultureInfo.InvariantCulture);
    

    【讨论】:

      【解决方案3】:

      如果您的字符串格式为dd/MM/yyyy,那么您必须使用具有指定格式的DateTime.ParseExact

      DateTime.ParseExact(dt, "dd/MM/yyyy", CultureInfo.InvariantCulture);
      

      任何其他方法都会尝试根据当前文化的规则解释字符串 - 正如您所发现的那样,这将失败。

      【讨论】:

        【解决方案4】:

        为什么不使用ToShortDateTimeString()

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-09-03
          • 1970-01-01
          • 1970-01-01
          • 2016-09-29
          • 1970-01-01
          • 2017-06-24
          • 1970-01-01
          相关资源
          最近更新 更多