简体   繁体   English

C# - DateTime.TryParse问题 - 为什么它不喜欢我的日期字符串表示?

[英]C# - DateTime.TryParse issue - why doesn't it like my string representation of my date?

Here's my code: 这是我的代码:

            DateTime Dob = Convert.ToDateTime("1/1/1800");
            DateTime Dod = Convert.ToDateTime("1/1/1800");

            if (!DateTime.TryParse(p.birthday, out Dob) && !DateTime.TryParse(p.deathday, out Dod))
            {
                // handle error
            }

p.birthday is: p.birthday是:

在此输入图像描述

p.deathday is: p.deathday是:

在此输入图像描述

When the .TryParse() code hits, my DateTime object for Dob is: .TryParse()代码命中时,我的Dob的DateTime对象是:

在此输入图像描述

And the DateTime object for Dod is: 而Dod的DateTime对象是:

在此输入图像描述

QUESTION : Why is Dod still "1-1-1800" (the initial value I assigned), but Dob is set correctly? 问题 :为什么Dod仍然是“1-1-1800”(我指定的初始值),但Dob设置正确? Is there something about the Dod value of "2007-02-28" that it doesn't like? 关于“2007-02-28”的Dod值有什么不喜欢的吗?

DateTime.TryParse(p.birthday, out Dob) successfully converts the string to DateTime , so it returns true. DateTime.TryParse(p.birthday, out Dob)成功将string转换为DateTime ,因此返回true。 You invert this with ! 你用它来反转! , giving false. 给予假。

When the execution gets to the && operator, it sees the first operand is already false , so doesn't bother executing the second operand. 当执行到达&&运算符时,它看到第一个操作数已经为false ,因此不会打扰执行第二个操作数。

You could either execute both beforehand, or use the non-shortcut AND operator, & . 您既可以预先执行,也可以使用非快捷方式AND运算符&

Edit: Or 编辑:或

if (!(DateTime.TryParse(p.birthday, out Dob) || DateTime.TryParse(p.deathday, out Dod)))
{
    ...
}

The reason is that its executing !(DateTime.TryParse(p.birthday, out Dob) and returning false. Therefore !DateTime.TryParse(p.deathday, out Dod) is not executed. 原因是它正在执行!(DateTime.TryParse(p.birthday,out Dob)并返回false。因此!DateTime.TryParse(p.deathday,out Dod)不会被执行。

According to 根据

http://msdn.microsoft.com/en-us/library/2a723cdk.aspx

x && y

if x is false, y is not evaluated, because the result of the 
AND operation is false no matter what the value of y is. This is known as 
"short-circuit" evaluation.

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

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