Subtract DateOnly in C#

Viewed 952

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'
5 Answers

Conceptually DateOnly represents an entire day, not midnight or any other specific time on a given day, such that subtracting one DateOnly from another cannot logically return a TimeSpan as with DateTime's subtraction operator.

If you want to perform arithmetic on DateOnlys, you need to be explicit about the desired unit.

DateOnly has a DayNumber property, that returns the number of whole days since 01/01/0001, so if you want to determine the number of whole days between 2 DateOnly values, you can do the following:

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

var daysDifference = d.DayNumber - e.DayNumber;

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;

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.

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.

Consider this: June 2, 2022 - June 1, 2022 = ? Is the answer 1 or is the answer 2? It encompasses 2 full days, but the difference is 1. By forcing us to use DayNumber, there is only one possible answer.

Related