How to check if DateTime is null
Solution 1
A DateTime
itself can't be null - it's cleanest to use DateTime?
aka Nullable<DateTime>
to represent nullable values.
It's not clear what CalendarFrom
and CalendarTo
are, but they may not support Nullable<DateTime>
themselves - but it would be a good idea to centralize the conversion here so you can use Nullable<DateTime>
everywhere other than where you're directly using CalendarFrom
and CalendarTo
.
Solution 2
DateTime
is a struct and so it can never be null.
I can think of two options:
If you really want to support null, use
DateTime?
to create a nullable DateTime.Alternatively, it may be appropriate in your application to simply set a
DateTime
value to a default value that indicates no real value has been set. For this default value, you could use eitherdefault(DateTime)
or something likeDateTime.MinValue
.
Solution 3
I am not sure what are your CalenderFrom and CalenderTo are; but I am assuming that they are static classess. Based on that assumption, this is how I would write this code.
public static class CalendarFrom
{
public static DateTime SelectedFrom { get; set; }
}
public static class CalendarTo
{
public static DateTime SelectedDate { get; set; }
}
DateTime? startDate = CalendarFrom.SelectedFrom;
DateTime? endDate = CalendarTo.SelectedDate;
if (startDate.HasValue
&& ( startDate.Value != DateTime.MaxValue || startDate.Value != DateTime.MinValue))
{
}
user1202765
Updated on May 03, 2020Comments
-
user1202765 almost 4 years
I have my two
DateTime
as follow:DateTime startDate = CalendarFrom.SelectedDate; DateTime endDate = CalendarTo.SelectedDate;
Now, I want to check if the
startDate
andendDate
is selected or not. As I know, we cannot assign null toDateTime
so I write in this way:if (startDate == DateTime.MinValue && endDate == DateTime.MinValue) { // actions here }
However I realise that for the
endDate
, it is not "1/1/0001 12:00:00 AM" so it cannot be checked by usingDateTime.MinValue
.I would like to know how will I be able to do checking for the
endDate
. Thanks!