I have my two DateTime
as follow:
DateTime startDate = CalendarFrom.SelectedDate;
DateTime endDate = CalendarTo.SelectedDate;
Now, I want to check if the startDate
and endDate
is selected or not. As I know, we cannot assign null to DateTime
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 using DateTime.MinValue
.
I would like to know how will I be able to do checking for the endDate
. Thanks!
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
.
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 either default(DateTime)
or something like DateTime.MinValue
.
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))
{
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.