Home > Enterprise >  Compare DateOnly values with DateTime. Shouldn't it be possible?
Compare DateOnly values with DateTime. Shouldn't it be possible?

Time:12-25

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 this error:

Operator '>' cannot be applied to operands of type 'DateTime' and 'DateOnly'

Even there is no built-in property to get the DateOnly from a DateTime without coding some custom extension methods nor the DateOnly.Compare methods supports comparing to DateTime type. The story is the same for TimeOnly If I am not missing something, what is the correct way of comparing this two type?

Update:

Just found It is not even possible to use these type 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...

CodePudding user response:

You can use the following methods to convert either to DateOnly or to DateTime, depending on what you need in the end.

var d = DateOnly.FromDateTime(DateTime.Now);
var dt = d.ToDateTime(TimeOnly.MinValue); // or whatever time you want

CodePudding user response:

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.

CodePudding user response:

This can work but you need to do a little fandangling.

I.E. Convert either DateOnly or DateTime to string then convert it to the other format then use compare. Off the top of my head, I do not know the exact code but it will look like this:

DateOnly origDO;// = some value;
DateTime origDT;// = some value;

string dTString = origDT.ToString("yyyy-MM-dd HH:mm:ss");
DateOnly convertedDO = DateOnly.Parse(dTString);

//-1 = <, 0 = ==, 1 = >
DateOnly.Compare(origDO, convertedDO);

The best way, is probably to use the base conversions that gSharp showed and then use the default comparison that I showed.

Don't forget that you can always write your own comparison at any time. So, DateOnly.Day > DateTime.Day

  • Related