Today I am writing again to bring you a library that will help us with the handling of dates in JavaScript, yes, as we all know the handling of dates in JavaScript is not very intuitive.
🤔 Why use dayjs?
Basically the justification for using dayjs is to simplify the handling of dates in JavaScript.
It is a fairly widespread library and which you have probably heard of already, it was presented a while ago as an alternative to Moment which is not recommended for use today, the main reason is the weight and the appearance of new alternatives that offer more modern and lighter solutions, dayjs is an example of this.
Moment
see more here
Dayjs
see more here
It is very light because it takes advantage of the Treeshaking since the library is fully extensible through plugins that we will add depending on the needs that arise, in this way we will only import the things we need.
🧪 Some examples
Now we will go to see some examples where its use would be justified compared to the native API, either for simplicity, readability or also to prevent possible errors.
We are going to review some of the most interesting functionalities that dayjs offers us.
🧹 Without plugins
Get difference in days between two dates
Check if the given date is valid or not
Get the number of days in the month
Add days, months, years, hours, minutes, seconds etc.
Subtract days, months, years, hours, minutes, seconds etc
âš¡ Extending the functionality through plugins
RelativeTime
Get time difference in string format between current date and given date using Spanish locale
WeekOfYear
Get week of year
IsSameOrAfter
Check if one date is equal to or greater than another
MinMax
Get the highest date or the lowest date among the dates of an array
IsBetween
Check if the given date is within the indicated date range
AdvancedFormat
Vitamin default formatting options
As can be seen in the examples above, the API is quite simple and readable, it seems to me without a doubt a great option if we need to solve some other complex function with dates in JavaScript.
For view more information go to official dayjs docs.
Thanks for reading me. 😊