'Subtract DateOnly in C#

In C# I can't use subtraction with DateOnly variables, unlike DateTime. Is there any explanation?

  var a = new DateTime(2000, 01, 01);
  var b = new DateTime(1999, 01, 01);

  //var c = a.Subtract(b);
  var c = a - b;

  var d = new DateOnly(2000, 01, 01);
  var e = new DateOnly(1999, 01, 01);

  var f = d - e; // Error - Operator '-' cannot be applied to operands of type 'DateOnly' and 'DateOnly'


Solution 1:[1]

You can use DayNumber property to do the subtraction, f will hold the number of days between d and e.

var f = d.DayNumber - e.DayNumber;

Solution 2:[2]

I don't know an exact reason as to why they haven't made it possible. But if you look at the documententation DateOnly it doesn't contain the operator addition and subtraction. DateTime does.

Solution 3:[3]

To answer your question why - DateOnly in operators section it just doesn't have subtraction implemented while DateTime does have one. What you can do is create your own extension similar to this one.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Scott Mildenberger
Solution 2 rbdeenk
Solution 3 Kęstutis Ramulionis