【问题标题】:Any difference between DateTime.Parse and Convert.ToDateTime?DateTime.Parse 和 Convert.ToDateTime 之间有什么区别?
【发布时间】:2012-01-01 19:31:00
【问题描述】:

有什么区别

Convert.ToDateTime

和

DateTime.Parse

哪个更快或更安全?

【问题讨论】:

标签: c# asp.net datetime


【解决方案1】:

根据answer on another forum from Jon Skeet...

Convert.ToDateTime 在内部使用 DateTime.Parse,当前 文化 - 除非你将它传递给 null,在这种情况下它会返回 DateTime.MinValue.

如果您不确定字符串是否为有效的DateTime,则两者都不使用,而是使用DateTime.TryParse()

如果您确定字符串是有效的DateTime,并且您知道格式,您还可以考虑使用DateTime.ParseExact() 或DateTime.TryParseExact() 方法。

【讨论】:

  • “简而言之,Convert.ToDateTime() 消除了设置 CultureInfo 所需的代码,而您必须这样做才能使用 DateTime.Parse()”这不是真的。您不必将 CultureInfo 设置为使用 DateTime.Parse()。 DateTime.Parse 有一个重载,它只需要 1 个字符串,没有其他内容,它使用当前的文化信息,而无需您传递它。
【解决方案2】:

DateTime.Parse 将在传递空字符串时抛出 Exception,Convert.ToDateTime 将在传递空值时返回 DateTime.MinValue。

【讨论】:

    【解决方案3】:

    DateTime.Parse 有一个重载,它只需要一个 String 而没有其他任何东西,它使用当前的 Locale 信息,而无需您传递它。

    【讨论】:

      【解决方案4】:

      以字符串为输入参数的Convert.ToDateTime的重载,内部调用DateTime.Parse。下面是 Convert.ToDateTime 的实现。

      public static DateTime ToDateTime(string value)
      {
          if (value == null)
          {
              return new DateTime(0L);
          }
          return DateTime.Parse(value, CultureInfo.CurrentCulture);
      }
      

      其他重载时,将参数转换为IConvertible接口,然后调用对应的ToDateTime方法。

      public static DateTime ToDateTime(ushort value)
      {
          return ((IConvertible) value).ToDateTime(null);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-05-08
        • 2018-12-23
        • 2010-11-07
        • 2014-07-20
        • 2011-03-01
        • 2013-02-20
        • 2021-04-10
        相关资源
        最近更新 更多