C# 使用DateTime.ParseExact分析时,字符串的格式不正确

C# 使用DateTime.ParseExact分析时,字符串的格式不正确,c#,parsing,C#,Parsing,当我尝试将此字符串解析为日期时: 1.05.2016 使用此代码: var startDate = DateTime.ParseExact(Console.ReadLine(), "dd.m.yyyy", CultureInfo.InvariantCulture); 出现以下错误: Unhandled Exception: System.FormatException: String was not recognized as a valid DateTime.

当我尝试将此字符串解析为日期时:

1.05.2016
使用此代码:

var startDate = DateTime.ParseExact(Console.ReadLine(),
              "dd.m.yyyy", CultureInfo.InvariantCulture);
出现以下错误:

Unhandled Exception: System.FormatException: String was not recognized as a valid DateTime.
   at System.DateTimeParse.ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style)
   at System.DateTime.ParseExact(String s, String format, IFormatProvider provider)
   at _09.Holidays_Between_Two_Dates.Program.Main(String[] args) in C:\Users\martin\documents\visual studio 2015\Projects\Methods. Debugging - Troubleshooting Code\09. Holidays Between Two Dates\09. Holidays Between Two Dates.cs:line 15

有人能帮忙吗?提前感谢。

请更正格式,因为输入的日期时间格式和提供的格式必须匹配

对于您的输入
1.05.2016
,您可以使用

var startDate = DateTime.ParseExact(Console.ReadLine(),
              "d.MM.yyyy", CultureInfo.InvariantCulture);
但日期并不总是一位数,因此最好使用两位数
01.05.2016

var startDate = DateTime.ParseExact(Console.ReadLine(),
              "dd.MM.yyyy", CultureInfo.InvariantCulture);

更正格式,因为输入日期时间格式和提供的格式必须匹配

对于您的输入
1.05.2016
,您可以使用

var startDate = DateTime.ParseExact(Console.ReadLine(),
              "d.MM.yyyy", CultureInfo.InvariantCulture);
但日期并不总是一位数,因此最好使用两位数
01.05.2016

var startDate = DateTime.ParseExact(Console.ReadLine(),
              "dd.MM.yyyy", CultureInfo.InvariantCulture);

您能从Console.Readline()再次检查您的输入吗?也许它包含回车符或其他非法字符?我在LinqPad中运行了以下程序:

DateTime.ParseExact("1.05.2016","d.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture).Dump();

并返回“01/05/2016 00:00:00”

您能从Console.Readline()再次检查您的输入吗?也许它包含回车符或其他非法字符?我在LinqPad中运行了以下程序:

DateTime.ParseExact("1.05.2016","d.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture).Dump();
并返回“01/05/2016 00:00:00”

“M”代表月,“M”代表分钟。请确保使用正确的:

var startDate = DateTime.ParseExact(Console.ReadLine(),
             "dd.M.yyyy", CultureInfo.InvariantCulture);
“M”代表月,“M”代表分钟。请确保使用正确的:

var startDate = DateTime.ParseExact(Console.ReadLine(),
             "dd.M.yyyy", CultureInfo.InvariantCulture);

请尝试将格式设置为“d.MM.yyyy”尝试将格式设置为“d.MM.yyyy”他为什么必须更改输入?为了安全起见,不是所有的时间日期都是一位数,但可以省略。我不明白你说的是什么。例如,使用“d.MM.yyyy”作为格式,将正确解析
11.05.2016
。它不会将日期限制为1位数。Pikoh是正确的。未添加的月份号(
d
)和填充的月份号(
dd
)仅在格式化时起作用,而在解析时起作用。使用的格式也可以是
“d.M.yyyy”
,它仍然可以工作-只有年份必须保持为
yyyy
。他为什么必须更改输入?为了安全起见,因为不是所有的时间日期都是个位数,但可以省略。我不明白你说什么。例如,使用“d.MM.yyyy”作为格式,将正确解析
11.05.2016
。它不会将日期限制为1位数。Pikoh是正确的。未添加的月份号(
d
)和填充的月份号(
dd
)仅在格式化时起作用,而在解析时起作用。使用的格式也可以是
“d.M.yyyy”
,它仍然有效-只有年份必须保持为
yyyy