为什么这个日期时间解析总是失败?
有人能看到我在这里做错了什么吗? Assert.IsTrue(parses)
总是失败。
[TestMethod]
public void Can_Parse_To_DateTime()
{
DateTime expected = new DateTime(2011, 10, 19, 16, 01, 59);
DateTime actual;
string value = "Wed Oct 19 16:01:59 PDT 2011";
string mask = "ddd MMM dd HH:mm:ss xxx YYYY";
bool parses = DateTime.TryParseExact(value, mask,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out actual);
Assert.IsTrue(parses);
Assert.AreEqual(expected, actual);
}
我也尝试过,结果相同:
[TestMethod]
public void parsing()
{
DateTime expected = new DateTime(2011, 10, 19, 16, 01, 59);
DateTime actual;
string value = "Wed Oct 19 16:01:59 PDT 2011";
string mask = "ddd MMM dd HH:mm:ss YYYY"; // note removal of "xxx "
value = value.Remove(20, 4); // removal of the "PDT "
bool parses = DateTime.TryParseExact(value, mask,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out actual);
Assert.IsTrue(parses);
Assert.AreEqual(expected, actual);
}
Can anyone see what I'm doing wrong here? The Assert.IsTrue(parses)
always fails.
[TestMethod]
public void Can_Parse_To_DateTime()
{
DateTime expected = new DateTime(2011, 10, 19, 16, 01, 59);
DateTime actual;
string value = "Wed Oct 19 16:01:59 PDT 2011";
string mask = "ddd MMM dd HH:mm:ss xxx YYYY";
bool parses = DateTime.TryParseExact(value, mask,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out actual);
Assert.IsTrue(parses);
Assert.AreEqual(expected, actual);
}
I have also tried it thus, with the same result:
[TestMethod]
public void parsing()
{
DateTime expected = new DateTime(2011, 10, 19, 16, 01, 59);
DateTime actual;
string value = "Wed Oct 19 16:01:59 PDT 2011";
string mask = "ddd MMM dd HH:mm:ss YYYY"; // note removal of "xxx "
value = value.Remove(20, 4); // removal of the "PDT "
bool parses = DateTime.TryParseExact(value, mask,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out actual);
Assert.IsTrue(parses);
Assert.AreEqual(expected, actual);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如 Matt Hamilton 所指出的,
yyyy
必须是小写。而xxx
是完全无效的。您始终可以使用反向方法DateTime.ToString(format,CultureInfo.InvariantCulture)
测试格式字符串。As noted by Matt Hamilton,
yyyy
must be lowercase. Andxxx
is totally invalid. You can always test your format string using reverse methodDateTime.ToString(format,CultureInfo.InvariantCulture)
.