[英]DateTime.parse string was not recognised
I can't understand why my string value keeps throwing an exception for what should be a valid string. 我无法理解为什么我的字符串值不断抛出应该是有效字符串的异常。 I have a string date in the format
"30/09/2016 14:55:00"
(called myDate
) and have tried the following to get it into a datetime format: 我有一个格式为
"30/09/2016 14:55:00"
(名为myDate
)的字符串日期,并尝试以下内容将其转换为日期时间格式:
DateTime.ParseExact(myDate, "dd/MM/yyyy HH:mm:ss", null);
DateTime.ParseExact(myDate, "dd/MM/yyyy HH:mm:ss", CultureInfo.CurrentCulture);
DateTime.Parse(myDate);
I can't see where I've gone wrong, is there something I've missed? 我看不出哪里出错了,有什么我错过的吗?
EDIT: 编辑:
Current value of myDate myDate的当前值
Keeps context when parse is called 调用解析时保留上下文
The same is also true for all other versions of parsing a string to DateTime 对于将字符串解析为DateTime的所有其他版本也是如此
It looks like you have extra unwanted double quotes in your string. 看起来你的字符串中有额外的不需要的双引号。
Try this and see if it works: 试试这个,看它是否有效:
var date = DateTime.ParseExact(myDate.Trim('\"'), "dd/MM/yyyy HH:mm:ss", CultureInfo.CurrentCulture);
You string contains additional quotes which you should remove before calling DateTime.Parse
. 您的字符串包含在调用
DateTime.Parse
之前应删除的其他引号。 You can remove the quotes by calling 您可以通过调用删除引号
myDate = myDate.Trim('"');
DateTime.ParseExact(myDate, "dd/MM/yyyy HH:mm:ss", null);
The problem is that your string has extra "
and then when you parse it throws an exception. Your string of "30/09/2016 14:55:00"
is actually \\""30/09/2016 14:55:00\\""
问题是你的字符串有额外的
"
然后当你解析它时抛出异常。你的字符串"30/09/2016 14:55:00"
实际上是\\""30/09/2016 14:55:00\\""
"30/09/2016 14:55:00"
\\""30/09/2016 14:55:00\\""
Remove the \\"
and then parse: 删除
\\"
然后解析:
string myDate = "\"30/09/2016 14:55:00\"";
var result = DateTime.ParseExact(myDate.Replace("\"",""), "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Or because it is always at the ends of the string you can use the .Trim
method 或者因为它总是在字符串的末尾,所以您可以使用
.Trim
方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.