Skip to content

Comment on Fix date-handling bug when today’s date is later than the target month

Comments

The fix is to change things like this:

  targetEndDate = new Date();
  targetEndDate.setFullYear( endDate.getFullYear() );
  targetEndDate.setMonth( endDate.getMonth() );
  targetEndDate.setDate( endDate.getDate() );
to
  targetEndDate = new Date();
  targetEndDate.setFullYear(
    endDate.getFullYear(),
    endDate.getMonth(),
    endDate.getDate());
That works because setFullYear has a three argument form that takes the year, month, and date avoiding the inconsistency that can arise by setting those one at a time.

But you know what else has a three argument for that take the year, month, and date? The Date constructor.

So why not fix it like this?

  targetEndDate = new Date(
    endDate.getFullYear(),
    endDate.getMonth(),
    endDate.getDate());
Using the empty constructor would initial the object with the current date and time, but they promptly overwrite those.

The Date construction also has a form that takes another Date object, so I wonder if they could have simple used:

  targetEndDate = new Date(endDate);
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.