Using .Net 6 and VS2022 , consider this code:
DateOnly dateOnly= new DateOnly(2022,12,24);
DateTime dateTime = DateTime.Now;
if (dateTime > dateOnly)
{
}
It will result in this error:
Operator '>' cannot be applied to operands of type 'DateTime' and 'DateOnly'
Even there are no built-in properties to get the DateOnly
from a DateTime
without coding some custom extension methods nor the DateOnly.Compare
methods support comparing to the DateTime
type. The story is the same for TimeOnly
If I am not missing something, what is the correct way of comparing these two types?
Update:
Just found It is not even possible to use these types just like other types in the webapi query parameters! Also EF core 6 does not have build-in support for these types in SqlClient!
Maybe it would be better to delay using these types...
You can get the DateOnly
from DateTime like this.
DateOnly dateOnly = DateOnly.FromDateTime(dateTime);
Then you can use the CompareTo method to compare both DateOnly.
Same concept is for TimeOnly, there is a TimeOnly.FromDateTime
method.