Comparing dates in C # with zero in mind

I am new to C #. I compare two dates when one is entered by the user and the other is the sytem date date. I have a code that works when it stands where the obstacle happened - how to handle null values. The base code I have is:

if (mydate.ToShortDateString() != TodaysDate.ToShortDateString())

{
//Error Messaage
}

else
{
//do some code
}

Any feedback would be appreciated.

+3
source share
3 answers

Why do you convert them to strings? Why not just compare date parts with them, as in date1.Date != date2.Date.

+2
source

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

As for handling this error, it depends on whether the null value for mydate is considered an error or not. If this is a mistake, you can do:

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

, :

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

mydate DateTime?, DateTime, DateTime.MinValue, (DateTime.MinValue DateTime)

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

Use? Operator:

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

else
{
//do some code
}
0
source

Source: https://habr.com/ru/post/1750283/


All Articles