DEV Community

Clark Johnson
Clark Johnson

Posted on

JS Date vs Moment.js: A Really Simple Comparison

Here's an exercise I wanted to share as part of my own efforts in learning out loud.

As part of a React project I'm working on, I needed to create and array containing the dates for the current month.

While composing the function I realized I would need to perform arithmetic on date objects. I could use the JS Date object directly, or I could make use of the methods provided by the moment.js library.

Moment.js

Implementing my function using the addon library allows use of the add method to increment a date. In the function below, day is a moment.js object.

function calendarDays(day) {
    const days = []
    day.date(1)
    day.add(-(day.day() + 1), "d")
    for (let i = 1; i <= 42; i++) {
        day.add(1, "d")
        days[i] = { day: day.date(), month: day.month() }
    }
    return days
}
Enter fullscreen mode Exit fullscreen mode

The function is called from the component and the array rendered using using the following code:

{calendarDays(moment()).map(day => <span key={day.day} className="calendar-day">{day.day}</span>)}
Enter fullscreen mode Exit fullscreen mode

The React profiler tool shows that the component renders in 2.2ms.
React Profiler for Moment.js Implementation

Javascript Object

function calendarDaysJS(day) {
    const days = []
    day.setDate(1)
    day.setDate(1 - day.getDay())
    for (let i = 1; i <= 42; i++) {
        days[i] = { day: day.getDate(), month: day.getMonth() }
        day.setDate(day.getDate() + 1)
    }
    return days
}
Enter fullscreen mode Exit fullscreen mode
{calendarDaysJS(new Date()).map(day => <span key={day.day} className="calendar-day">{day.day}</span>)}
Enter fullscreen mode Exit fullscreen mode

The React profiler reveals that the component renders in 1.3ms. That's a 40% improvement in efficiency.

React Profiler for Date Object Implementation

Conclusion

According to the explanation offered by moment.js, using the library for date arithmetic operations yields code that is more readable. My small test reveals that the there is definitely an efficiency tradeoff. As always, it is up to the development team to decide which is more important. As for myself, I am definitely leaning towards the reduced time benefits.

Happy coding!

Top comments (3)

Collapse
 
merri profile image
Vesa Piittinen

Tip: date-fns allows manipulation of native Date object with easy to understand utility functions.

Collapse
 
alwarg profile image
Alwar G
Collapse
 
clarkj99 profile image
Clark Johnson

Thank you! That's a really useful post. I've only used moment.js a few times and it's good to get new perspectives.