简体   繁体   English

在C#中将字符串转换为DateTime-无法将字符串识别为有效的DateTime

[英]Convert String to DateTime in C# - String was not recognized as a valid DateTime

I reviewed the question here: Convert string to datetime in C#.net 我在这里查看了问题: 在C#.net中将字符串转换为datetime

The format I'm trying to pass is only slightly different, but cannot get it to work. 我尝试传递的格式仅稍有不同,但无法正常使用。

My code: 我的代码:

var date = DateTime.ParseExact(@"28/06/2012 06:04:10 PM", @"dd/MM/yyyy hh:mm:ss tt", null);

So then I tried the example code from the question mentioned above: 因此,我尝试了上述问题的示例代码:

var date = DateTime.ParseExact(@"14/04/2010 10:14:49.PM", @"dd/MM/yyyy hh:mm:ss.tt", null);

That doesn't work either. 那也不行。 Both give me 都给我

System.FormatException
String was not recognized as a valid DateTime.

Any ideas would be greatly appreciated! 任何想法将不胜感激! Thanks! 谢谢!

The problem is localisation. 问题是本地化。

Consider these three statements: 考虑以下三个语句:

DateTime.ParseExact(@"14/04/2010 10:14:49.PM", @"dd/MM/yyyy hh:mm:ss.tt", new CultureInfo("fr-fr"))
DateTime.ParseExact(@"14/04/2010 10:14:49.PM", @"dd/MM/yyyy hh:mm:ss.tt", new CultureInfo("en"))
DateTime.ParseExact(@"14/04/2010 10:14:49.PM", @"dd/MM/yyyy hh:mm:ss.tt", CultureInfo.InvariantCulture)

The first will not work whereas the last two will. 前一个无效,而后两个无效。 In this case it is because the PM is not valid in fr-fr . 在这种情况下,这是因为PMfr-fr无效。 If you try this: 如果您尝试这样做:

DateTime.ParseExact(@"14/04/2010 10:14:49.", @"dd/MM/yyyy hh:mm:ss.tt", new CultureInfo("fr-fr"))

it will work fine. 它将正常工作。

As has been noted in comments other cultures may fail on other items. 正如评论中提到的,其他文化可能在其他项目上失败。 en-za uses a different date separator causing that to fail. en-za使用其他日期分隔符导致失败。

var dateString = "28/06/2012 06:04:10 PM";
DateTime dt = DateTime.ParseExact(dateString, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);

/ is date separator and probably in your culture it's not exactly / . /是日期分隔符,可能在您的文化中不完全是/ The same issue can occur with : , which is replaced with current culture time separator. 有可能发生同样的问题: ,这是替换当前区域性时间分隔符。 Try escaping both / and : : 尝试逃脱既/:

var date = DateTime.ParseExact(@"28/06/2012 06:04:10 PM", @"dd\/MM\/yyyy hh\:mm\:ss tt", null);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM