字符串未被识别为有效的日期时间.ParseExact - Just Date

本文关键字:ParseExact 时间 Just Date 日期 识别 有效 字符串 | 更新日期: 2023-09-27 17:55:22

我已经尝试了几种不同的格式字符串,但我无法让它解析这样的日期:

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

我错过了什么?!

字符串未被识别为有效的日期时间.ParseExact - Just Date

为了解析日期,您的格式需要相同。 将"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();
    }
}