【问题标题】:String was not recognized as a valid DateTime. ParseExact - Just Date字符串未被识别为有效的日期时间。 ParseExact - 只是日期
【发布时间】:2014-03-31 19:14:03
【问题描述】:

我尝试了几种不同的格式字符串,但无法解析日期,例如:

date = "10/16/13";
DateTime endDate = DateTime.ParseExact(date, "M-dd-yy", CultureInfo.InvariantCulture);

我错过了什么?!

【问题讨论】:

  • 你为什么使用破折号?你必须使用@"M\/dd\/yy"
  • 替换 / 由 - 或反之亦然
  • 也许你应该看看 ParseExact 到底做了什么。

标签: c# string datetime datetime-format


【解决方案1】:

为了解析日期,您的格式需要相同。将“M-dd-yy”更改为“M/dd/yy”假设月份为一位数,日期始终为两位数。

【讨论】:

    【解决方案2】:

    给你,这应该工作得很好。您只需要注意它将设置默认时间为 12:00 am,因为您没有在字符串中指定时间。

    class Program 
    {
        static void Main(string[] args)
        {
            string date = "10/16/13";
    
            //This is usually the safer way to go
            DateTime result;
            if(DateTime.TryParse(date, out result))
                Console.WriteLine(result);
    
            //I think this is what you were trying to accomplish
            DateTime result2 = Convert.ToDateTime(date, CultureInfo.InvariantCulture);
    
            Console.ReadKey();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-24
      • 1970-01-01
      相关资源
      最近更新 更多