How to use quarters in Day.js
This article will show how to work around a small gotcha in Day.js and show the library's code for the second round of the build size benchmark.
As I explained in the second article about date-fns, comparing the use of only one method skews our benchmark. Especially as one library is full-on tree-shaking and the other doesn't support it. So I developed a bit more complex example, and the article linked before shows it in date-fns.
My first try was straightforward, same code as I would use with Moment.js:
import dayjs from "dayjs"; const today = dayjs(), quarterStart = dayjs().startOf("quarter"), diffDays = today.diff(quarterStart, "days"); console.log("Yesterday was", dayjs().subtract(1, "day").toDate()); console.log( "The quarter started on", quarterStart.format("YYYY-MM-DD"), "and today, it is", diffDays, "days since then" );
To my surprise, the log I've got is:
The quarter started on 2021-08-06, and today, it is 0 days since then.
The quarter didn't start on the 6th of august.
import quarterOfYear from 'dayjs/plugin/quarterOfYear' dayjs.extend(quarterOfYear) dayjs('2010-04-01').quarter() // 2 dayjs('2010-04-01').quarter(2)
So in my example, I just needed to add 2 lines to have everything work as expected:
import dayjs from "dayjs"; +import quarterOfYear from "dayjs/plugin/quarterOfYear"; + +dayjs.extend(quarterOfYear); const today = dayjs(), quarterStart = dayjs().startOf("quarter"),
For sure, the first encounter with plugins in this library wasn't smooth. It looked more like a library bug than an incomplete import. I wonder if throwing an error or logging something in the consoles would be a better dev experience. Maybe now, knowing Day.js is not such a monolith, I'll expect some plugins import?
The final code builds:
- webpack - 7.39 KiB
- esbuild - 8KiB
In this article, we have walked through an update to Day.js code for the second round of the build size benchmark. Besides, we discussed the quarter plugin gotcha the library has.
Interested in reading more such articles from Marcin Wosinek?
Support the author by donating an amount of your choice.