Member-only story
Incrementing and Decrementing Dates in Javascript
In my day job for a London Council, I recently I had to build the front end for a reservation system where users could reserve appointment slots for a Covid-19 test. I was going to build it using Vanilla Javascript and ES6. How it was going to work, was that the backend, where the appointment slots were created would be provided to me as a JSON feed, so I just needed to be able to find a way to consume the feed and then build out the front end with the data.
This was all relatively straightforward to do, I fetched the JSON feed and was able to build out the relative parts of the application, until I came to the part where I had to build the date controls. The date controls would use a set of ‘previous’ and ‘next’ buttons, where clicking ‘previous’ would decrement the date by 1 day and the ‘next’ button would increment the date by 1 day. The url for the JSON feed would have a date in ISO-8601 format (YYYY-MM-DD) as a variable that if incremented or decremented, the updated url would be used to fetch the new JSON data.
Having never really worked much with dates in the past, and having used dayJS the few times when I had, my initial thought was to reach for it again. DayJS exists because working with dates in Javascript is usually a nightmare for most devs. However dayJS didn’t seem to offer what I was looking for, and would have been…