c# DateTime.ParseExact 错误
c# DateTime.ParseExact error
我有一个字符串未被识别为有效的日期时间错误。
遵循了 here. 中的一个例子,其中有一个例子说:
dateString = "15/06/2008 08:30";
format = "g";
provider = new CultureInfo("fr-FR");
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
这是我的代码:
string convertToString = string.Join("", dateTimeId);
DateTime parsedDateTime = DateTime.ParseExact(convertToString, "g", CultureInfo.InvariantCulture);
我将一个字符串数组转换为字符串,因为我正在读取一个日期时间值为“3/16/2002 9:20”的 csv 行。
我也尝试了 "MM/dd/yyyy HH:mm" 的格式,但仍然出现同样的错误。
如有任何提示或帮助,我们将不胜感激。
试试这个格式字符串
"M/dd/yyyy H:mm"
如果您为月份指定两个 M,为小时指定两个 H,则两者都需要一个前导零。
或者只使用 DateTime.Parse
应该可以。
Console.WriteLine(DateTime.Parse("3/16/2002 9:20", CultureInfo.InvariantCulture));
我越看这个越觉得 "g" 应该有效。它似乎只有在月份和小时都有前导零的情况下才有效,即使如果您使用它将 DateTime
格式化为 string
,它也不会放入前导零,至少对于 InvariantCulture
.
我有一个字符串未被识别为有效的日期时间错误。
遵循了 here. 中的一个例子,其中有一个例子说:
dateString = "15/06/2008 08:30";
format = "g";
provider = new CultureInfo("fr-FR");
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
这是我的代码:
string convertToString = string.Join("", dateTimeId);
DateTime parsedDateTime = DateTime.ParseExact(convertToString, "g", CultureInfo.InvariantCulture);
我将一个字符串数组转换为字符串,因为我正在读取一个日期时间值为“3/16/2002 9:20”的 csv 行。
我也尝试了 "MM/dd/yyyy HH:mm" 的格式,但仍然出现同样的错误。
如有任何提示或帮助,我们将不胜感激。
试试这个格式字符串
"M/dd/yyyy H:mm"
如果您为月份指定两个 M,为小时指定两个 H,则两者都需要一个前导零。
或者只使用 DateTime.Parse
应该可以。
Console.WriteLine(DateTime.Parse("3/16/2002 9:20", CultureInfo.InvariantCulture));
我越看这个越觉得 "g" 应该有效。它似乎只有在月份和小时都有前导零的情况下才有效,即使如果您使用它将 DateTime
格式化为 string
,它也不会放入前导零,至少对于 InvariantCulture
.