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'
Conceptually
DateOnlyrepresents an entire day, not midnight or any other specific time on a given day, such that subtracting oneDateOnlyfrom another cannot logically return aTimeSpanas withDateTime's subtraction operator.If you want to perform arithmetic on
DateOnlys, you need to be explicit about the desired unit.DateOnlyhas aDayNumberproperty, that returns the number of whole days since 01/01/0001, so if you want to determine the number of whole days between 2DateOnlyvalues, you can do the following: