C# DateTime.ParseExact

2019-03-22 12:39发布

I have a tab delimited file which is being parsed and then inserted into a database. When I run into the date column, I have trouble parsing it.

The code I have is:

var insert = DateTime.ParseExact(line[i], "d/M/yyyy h:mm", CultureInfo.InvariantCulture);

The string in line[i] is in the format 7/7/2011 10:48 The exception I get says

The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.

4条回答
该账号已被封号
2楼-- · 2019-03-22 13:04

It's probably the same problem with cultures as presented in this related SO-thread: Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

You already specified the culture, so try escaping the slashes.

查看更多
姐就是有狂的资本
3楼-- · 2019-03-22 13:17

try this

var  insert = DateTime.ParseExact(line[i], "M/d/yyyy h:mm", CultureInfo.InvariantCulture);
查看更多
Viruses.
4楼-- · 2019-03-22 13:18

That's because you have the Date in American format in line[i] and UK format in the FormatString.

11/20/2011
M / d/yyyy

I'm guessing you might need to change the FormatString to:

"M/d/yyyy h:mm"
查看更多
贪生不怕死
5楼-- · 2019-03-22 13:24

Your format string is wrong. Change it to

insert = DateTime.ParseExact(line[i], "M/d/yyyy hh:mm", CultureInfo.InvariantCulture);
查看更多
登录 后发表回答