开发者

comparing dates in c# taking null value into account

开发者 https://www.devze.com 2023-01-03 20:48 出处:网络
I am new to c#. I am comparing two dates where one is entered by user and the other one is sytem date time. i have the code working as it stands where the obstacle has occured is how to cater for null

I am new to c#. I am comparing two dates where one is entered by user and the other one is sytem date time. i have the code working as it stands where the obstacle has occured is how to cater for null values. the basic code I have is:

if (mydate.ToSho开发者_运维技巧rtDateString() != TodaysDate.ToShortDateString())

{
//Error Messaage
}

else
{
//do some code
}

Any feedback will be appreciated


Why are you converting them to strings? Why not just compare the date portions of them as in date1.Date != date2.Date.


You can declare mydate as DateTime?, then it can hold null values.

As to how to handle the error, it depends on whether having a null value for mydate is considered an error or not. If it's an error, you could do:

if (mydate == null || mydate.ToShortDateString() != TodaysDate.ToShortDateString()) {
    // error
}

If it's not an error condition, you could do:

if (mydate != null && mydate.ToShortDateString() != TodaysDate.ToShortDateString()) {
    // error
}

If you don't declare mydate as DateTime? but instead just declare it as DateTime, then you can check for DateTime.MinValue, like this (DateTime.MinValue is the default value for a DateTime variable):

if (mydate == DateTime.MinValue || mydate.ToShortDateString() != TodaysDate.ToShortDateString()) {
    // error
}


Use the ?? operator:

if ((mydate??DateTime.MinValue).ToShortDateString() != TodaysDate.ToShortDateString())
{
//Error Messaage
}

else
{
//do some code
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号