Easily Work with Dates in JavaScript using dayjs and comparision with date-fns
📒

Easily Work with Dates in JavaScript using dayjs and comparision with date-fns

 
 
JavaScript provides a built-in Date object that allows developers to work with dates and times. With the Date object, you can perform various operations, such as getting the current date and time, comparing dates, and formatting dates.
 
The Date object is accessed through the global Date function. To create a Date object, you can pass a date string to the Date function, like this:
 
let date = new Date("December 14, 2022");
 
You can also create a Date object using individual date and time values, like this:
 
let date = new Date(2022, 11, 14, 12, 0, 0);
The Date object has several methods that allow you to get information about the date and time, such as the year, month, day, hour, minute, and second. For example, you can use the getFullYear() method to get the year, and the getMonth() method to get the month.
 
let date = new Date("December 14, 2022"); let year = date.getFullYear(); // 2022 let month = date.getMonth(); // 11 // ...
 
In addition to the built-in Date object, there are also several libraries that make it easier to work with dates in JavaScript.

Dayjs

Day.js is a small, fast, and immutable date library that provides a similar API to Moment.js. To install day.js, you can use the npm package manager, like this:
 
npm install dayjs
 

1. Basic Getting the Current Date and Time with dayjs in JavaScript

 
Once you've installed day.js, you can create a day.js object using the dayjs() function,
// Get the current date and time using dayjs const now = dayjs(); // Format the date and time console.log(now.format('MM/DD/YYYY, h:mm:ss a')); // 12/14/2022, 10:15:30 am // Parse a date string using dayjs const dateString = '2022-12-14'; const date = dayjs(dateString); // Format the date using dayjs console.log(date.format('MM/DD/YYYY')); // 12/14/2022
 

2. Manipulating Dates with dayjs in JavaScript

// Parse a date string using dayjs const dateString = '2022-12-14'; const date = dayjs(dateString); // Add one month to the date const nextMonth = date.add(1, 'month'); // Subtract two days from the date const previousTwoDays = date.subtract(2, 'day'); // Check if the date is before a given date const isBefore = date.isBefore('2022-12-20');
 

3. Comparing Dates with dayjs in JavaScript”

// let's create some dates to work with const date1 = dayjs('2022-12-14'); const date2 = dayjs('2022-12-15'); // Check if date1 is before date2 console.log(date1.isBefore(date2)); // Output: true // Check if date1 is after date2 console.log(date1.isAfter(date2)); // Output: false // Check if date1 is the same as date2 console.log(date1.isSame(date2)); // Output: false
 
You can also compare two dates by using the .isSame() method, which returns a boolean value indicating whether two dates are the same.
 
const firstDate = dayjs('2022-12-01'); const secondDate = dayjs('2022-12-31'); const thirdDate = dayjs('2022-12-01'); // Check if the first and second dates are the same console.log(firstDate.isSame(secondDate)); // Output: false // Check if the first and second dates are the same year console.log(firstDate.isSame(secondDate,'year')); // Output: true // Check if the first and third dates are the same console.log(firstDate.isSame(thirdDate)); // Output: true
 
You can also specify the level of precision at which to compare the dates, using the .isSame() method's second argument. For example, you can compare only the year, month, or day, by passing in the string 'year', 'month', or 'day', respectively.
 

4. Sorting Dates with dayjs in JavaScript

The sort method can be used to sort an array of dates in ascending or descending order. For example:
let dates = [ dayjs('2022-12-14T12:00:00'), dayjs('2022-12-13T12:00:00'), dayjs('2022-12-15T12:00:00')]; dates.sort((a, b) => a.diff(b)); // sort dates in ascending order dates.sort((a, b) => b.diff(a)); // sort dates in descending order
 
The min and max methods can be used to find the earliest and latest dates in an array of dates, respectively. For example:
 
let dates = [ dayjs('2022-12-14T12:00:00'), dayjs('2022-12-13T12:00:00'), dayjs('2022-12-15T12:00:00')]; let earliestDate = dates.reduce((a, b) => a.isBefore(b) ? a : b); let latestDate = dates.reduce((a, b) => a.isAfter(b) ? a : b); console.log(earliestDate) // '17:10 12/14/2022' console.log(latestDate) // '17:10:14 2022-12-14'
 

5. From now

This dependent on RelativeTime plugin to work
 
RelativeTime adds .from .to .fromNow .toNow APIs to formats date to relative time strings (e.g. 3 hours ago). docs
 
If you pass true, you can get the value without the suffix.
 
import dayjs from "dayjs"; import relativeTime from "dayjs/plugin/relativeTime"; dayjs.extend(relativeTime); dayjs("1997-18-03").fromNow(); // '25 years ago' dayjs("1997-18-03").fromNow(true); // '25 years'
Range
Key
Sample Output
0 to 44 seconds
s
a few seconds ago
45 to 89 seconds
m
a minute ago
90 seconds to 44 minutes
mm
2 minutes ago ... 44 minutes ago
45 to 89 minutes
h
an hour ago
90 minutes to 21 hours
hh
2 hours ago ... 21 hours ago
22 to 35 hours
d
a day ago
36 hours to 25 days
dd
2 days ago ... 25 days ago
26 to 45 days
M
a month ago
46 days to 10 months
MM
2 months ago ... 10 months ago
11 months to 17months
y
a year ago
18 months+
yy
2 years ago ... 20 years ago
Check docs for customizing locales. ( Check docs )

Comparision date-fns dayjs

Two popular good libraries: Day.js and date-fns. Both libraries offer a range of methods for working with dates and times, and are known for their small size and performance.
 
We found that date-fns had the smallest size in our tests, coming in at just 1.6 KiB when using only one method. However, when using more methods, the size advantage of date-fns diminished, resulting in a final size of 3.63 KiB when using webpack and 3.6 KiB when using esbuild.
 
On the other hand, Day.js offers an API that is similar to that of Moment.js, making it an attractive option for projects that already use Moment.js. In our tests, Day.js was slightly larger than date-fns, with a size of 6.64 KiB when using webpack and 7.0 KiB when using esbuild. However, Day.js does require the use of plugins for some methods, which can increase the overall size of the library.
 
Overall, date-fns is the best choice for projects that are concerned about build size, while Day.js is a good option for projects that are looking to migrate from Moment.js.