Using Day.js to calculate the difference between two dates

In the Saber Commerce timesheet entries we need to calculate (quickly and accurately) the difference between two dates. Doing this in raw JS would be a pain to say the least, arguably feasible but not fun to code at all. So we searched for libraries that could help, and most examples of javascript date manipulation point to Moment.js for things like this. However, that project actually tells us (on it’s own site) not to use it because it’s no longer maintained and not efficient. Apparently that project is being replaced by Luxon, and it’s not clear if we could use that for similar date manipulations. Fortunately Day.js has been around for awhile now and it offers a stable and mature approach to date manipulation, including the handy .diff() function that we’re going to showcase today.

In order to use the DayJS .diff() function we’ll need to first have 2 dates (or dates and times) that are already parsed into DayJS date objects. For our purposes we use the native parsing option which is to pass a string in ISO 8601 format which looks like this:

ISO 8601 Date Format: 2018-04-04T16:00:00.000Z

The “T” and the “Z” are each there for aspects of timezone handling which we won’t delve into here for the sake of brevity. Obviously date and time manipulation can become a rabbit hole as there are a lot of coding considerations which all vary depending on exactly what you need to do. In most situations however, regardless of how dates and times are entered in the UX, you should usually be able to form an ISO 8601 string consistently of the date (in YYYY-MM-DD format) and then the time in HH:MM:SS format. For this example we’ll presume you’re not using milliseconds, or doing timezone manipulation.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *