Hacker News new | ask | show | jobs
by da_chicken 1772 days ago
> Plus/Increment/Add 1 month, does have one single meaning

No, it doesn't.

You walk in to the doctor's office on February 28. At the desk, you see another patient about to leave. They turn to the desk attendant and say, "I'll see you in a month for my follow-up."

What date is the other patient's next appointment? What if the date you walked in had been January 31?

Also, for what it's worth, in C#:

  DateTime x = new DateTime(2021, 1, 31);
  x.AddMonths(1); // Feb 28
  x.AddMonths(2); // March 31
  x.AddMonths(1).AddMonths(1); // March 28
1 comments

I explained it pretty clearly what you get when you add a month on January 31st. You get February 31st.

A month is a discrete unit of measure. It is not decomposable into any number of days.

When you increment a month, you get YYYY - (MM+1). Any higher significance is maintained, but irrelevant to the operation. (This applies to the hypothetical statement in the doctor's office, the specific day is indeterminant, but can be assumed the same as current day next month.)

The fact that not all possible days exist is orthogonal to the singular meaning of the operation. It's obviously not greatly valuable to an end-user, but the method of addressing the ambiguity involves a second operation that ensures validity.

End-users want an method that does both the addition and coercion, but you can create consistency if you follow the simple path I laid out in GP.

I'll use your syntax but with the strictly correct definition of the operation.

  Datetime x = new DateTime(2021, 1, 31);
  x.AddMonths(1); // DateTime(2021, 2, 31)
  x.AddMonths(2); // DateTime(2021, 3, 31)
  x.AddMonths(1).AddMonths(1); //DateTime(2021, 3, 31)

  // Ensure Valid, using a coerce to clamp overflows
  DateTime(2021, 2, 31).EnsureValid(); // Feb 28
  DateTime(2021, 3, 31).EnsureValid(); // Mar 31
  DateTime(2021, 4, 31).EnsureValid(); // Apr 30