[英]DateTime.ParseExact formats question
I have datetime strings that look can like any the following: 我有日期时间字符串看起来像以下任何一样:
"1 13 2009 2300", "1 14 2009 0", "1 14 2009 100" “1 13 2009 2300”,“1 14 2009 0”,“1 14 2009 100”
that I need to parse into a DateTime. 我需要解析为DateTime。
I have tried: 我试过了:
string[] sExpectedFormats = {"M d yyyy Hmm", "M d yyyy hmm", "M d yyyy 0"};
DateTime dtReportDateTime = DateTime.ParseExact(sReportDateTime,
sExpectedFormats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None);
but it fails on the third one "1 14 2009 100". 但它在第三个“1 14 2009 100”上失败了。 I am not sure what format to use for that?
我不确定使用什么格式?
To clarify, I get this data in a feed as a date part "1 14" and a time part "100", so am concatenating it so I can parse into a DateTime. 为了澄清,我在feed中将这些数据作为日期部分“1 14”和时间部分“100”得到,所以我将它连接起来以便我可以解析为DateTime。
Thanks 谢谢
I suspect that it's interpreting the "100" as "10" followed by "0" - ie parse the H or h as "10" and then fail to find two digits for the minutes. 我怀疑它将“100”解释为“10”后跟“0” - 即将H或h解析为“10”,然后找不到分钟的两位数。
Frankly I'd be tempted to manually reformat the string before parsing so that it always ends in 4 digits instead of 3. Reluctant as I am to recommend them usually, this does sound like a job for regular expressions :) 坦率地说,我很想在解析之前手动重新格式化字符串,这样它总是以4位而不是3位结束。不情愿,因为我通常会推荐它们,这听起来像是正则表达式的工作:)
Just as an aside, I'm not sure why you've got both the "H" and "h" formats - it's never going to match the second format, because anything valid for the second would have been valid for the first. 顺便说一句,我不确定你为什么同时拥有“H”和“h”格式 - 它永远不会匹配第二种格式,因为对第二种格式有效的东西对第一种格式有效。
If you fix up the string beforehand as I've suggested, you can then just use 如果你按照我的建议事先修好了字符串,那么你就可以使用了
{"M d yyyy HHmm", "M d yyyy 0"}
I think it fails because "hmm" = "100" is ambiguous between 1:00 AM or PM. 我认为它失败了,因为“hmm”=“100”在凌晨1点或PM之间是不明确的。 Maybe you should stick to "Hmm" or use "hmm tt" = "100 AM" format.
也许你应该坚持“嗯”或使用“hmm tt”=“100 AM”格式。
Edit: tried and failed. 编辑:尝试过但失败了。 What Jon said in his answer and my comment is true.
Jon在他的回答中说了什么,我的评论也是如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.