Search code examples
javascriptangulartypescriptecmascript-temporal

How to loop through the days in a calendar month using the temporal API


I am using the temporal API to create a simple calendar. I ran into 2 errors when trying to loop through the days in month of January. My goal with this loop is to visually create divs that match the amount of the days in the current calendar month in real time. Any help would greatly be appreciated! Here is a screenshot of my code enter image description here

I am getting these 2 errors listed below (don't pay attention to the blue line that looks like an error on 'daysinJanuary', it is my dictionary extension and has nothing to do with the problem at hand)

  • Operator '<=' cannot be applied to types 'PlainDate' and 'number'.ts(2365)

  • An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type.ts(2356)


Solution

  • I think you would probably have more insight into the error if you added types to your TS code matching the types that you expect, and let the TS compiler tell you where your expectations differ from the types that it computes.

    january is a Temporal.PlainDate denoting 2022-01-01, and january.daysInMonth is a number (in this case 31, because January 2022 has 31 days). So this is what the error is telling you: the <= operator doesn't have any meaning for a left-hand side of Temporal.PlainDate and a right-hand side of a number. (Is "January 1, 2022" more or less than "31"? Hard to say.)

    Likewise, addDays is another Temporal.PlainDate denoting 2022-01-02 (1 day later than january, because you added 1 day to it using the add() method) and so using the ++ operator on it doesn't have any meaning either. (Here, it does seem conceivable that incrementing a date might add 1 day to it; but that's not the case, adding is only done with the add() method.)

    If you want to create a number of divs that match the number of days in January, you might consider looping a number index from 1 to january.daysInMonth?