DEV Community

Cover image for Working with Date in Javascript: new Date() vs Day.js vs Moment.js
Syakir
Syakir

Posted on • Originally published at devaradise.com

Working with Date in Javascript: new Date() vs Day.js vs Moment.js

Checkout the original post https://devaradise.com/date-in-javascript-dayjs-momentjs/ to read with Table of Content

Handling dates and times is a common task in JavaScript development. While JavaScript's native Date object offers a variety of methods to work with dates, there are scenarios where using external libraries like Day.js or Moment.js can simplify your workflow and provide more robust solutions.

In this article, we’ll explore common cases that can be solved by JavaScript’s native Date object and those that are best handled by external libraries. We’ll also compare Day.js and Moment.js to help you choose the right tool for your needs.

Common Cases Solvable by Native JS Date

The native JavaScript Date object provides a range of methods for working with dates and times. Here are some common use cases where the native Date object is sufficient:

1. Creating Dates

const now = new Date(); // Current date and time
const specificDate = new Date('2024-07-16'); // Specific date
Enter fullscreen mode Exit fullscreen mode

2. Getting Date and Time Components

const now = new Date();
const year = now.getFullYear();
const month = now.getMonth() + 1; // Months are zero-indexed
const day = now.getDate();

const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();
Enter fullscreen mode Exit fullscreen mode

3. Setting Date and Time Components

const now = new Date();

now.setFullYear(2025);
now.setMonth(11); // December
now.setDate(25);

now.setHours(10);
now.setMinutes(11);
now.setSeconds(12);
Enter fullscreen mode Exit fullscreen mode

4. Date Arithmetic

const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
Enter fullscreen mode Exit fullscreen mode

5. Formatting Dates

const now = new Date();
const dateString = now.toDateString(); // Example: 'Tue Jul 16 2024'
const timeString = now.toTimeString(); // Example: '14:12:34 GMT+0200 (Central European Summer Time)'
Enter fullscreen mode Exit fullscreen mode

6. Parsing Dates

const parsedDate = new Date(Date.parse('2024-07-16T14:12:34Z'));
Enter fullscreen mode Exit fullscreen mode

7. Comparing Dates

const date1 = new Date('2024-07-16');
const date2 = new Date('2024-07-17');
const isSame = date1.getTime() === date2.getTime(); // false
const isBefore = date1.getTime() < date2.getTime(); // true
Enter fullscreen mode Exit fullscreen mode

8. Getting the Day of the Week

const dayOfWeek = now.getDay(); // 0 for Sunday, 1 for Monday, etc.
Enter fullscreen mode Exit fullscreen mode

9. Converting to UTC and ISO String

const now = new Date();
const isoDate = now.toISOString(); // 2024-07-22T11:30:59.827Z
const utcDate = now.toUTCString(); // Mon, 22 Jul 2024 11:30:42 GMT
Enter fullscreen mode Exit fullscreen mode

Calculating Date Differences

const date1 = new Date('2024-01-01');
const date2 = new Date('2024-12-31');
const differenceInTime = date2 - date1;
const differenceInDays = differenceInTime / (1000 * 3600 * 24);
console.log(differenceInDays);
Enter fullscreen mode Exit fullscreen mode

Cases Best Solved by External Libraries Like Day.js and Moment.js

While the native Date object covers basic date manipulation, certain tasks are more efficiently handled by external libraries like Day.js and Moment.js. Here are some scenarios where these libraries excel:

1. Advanced Formatting

// Day.js
const Day.jsDate = Day.js().format('YYYY-MM-DD HH:mm:ss');

// Moment.js
const momentDate = moment().format('YYYY-MM-DD HH:mm:ss');
Enter fullscreen mode Exit fullscreen mode

2. Relative Time

// Day.js
Day.js.extend(relativeTime); // require RelativeTime plugin
Day.js('2024-01-01').from(Day.js('2023-01-01')); // a year ago

// Moment.js
moment('2024-01-01').from(moment('2023-01-01')); // a year ago
Enter fullscreen mode Exit fullscreen mode

3. Time Zone Handling

Day.js.extend(utc);
Day.js.extend(timezone);
Day.js('2024-07-16 14:12:34').tz('America/New_York');

// Moment.js with moment-timezone
moment.tz('2024-07-16 14:12:34', 'America/New_York');
Enter fullscreen mode Exit fullscreen mode

4. Internationalization (i18n)

// Day.js
Day.js.locale('fr');
const frenchDate = Day.js().format('LLLL'); // dimanche 15 juillet 2012 11:01

// Moment.js
moment.locale('fr');
const frenchMomentDate = moment().format('LLLL'); // dimanche 15 juillet 2012 11:01
Enter fullscreen mode Exit fullscreen mode

5. Handling Invalid Dates

// Day.js
const invalidDay.js = Day.js('invalid date');
if (!invalidDay.js.isValid()) {
    console.log('Invalid date');
}

// Moment.js
const invalidMoment = moment('invalid date');
if (!invalidMoment.isValid()) {
    console.log('Invalid date');
}
Enter fullscreen mode Exit fullscreen mode

6. Parsing Complex Date Formats

// Day.js with customParseFormat plugin
Day.js.extend(customParseFormat);
const complexDate = Day.js('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z');

// Moment.js
const complexMoment = moment('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z');
Enter fullscreen mode Exit fullscreen mode

7. Working with Durations

// Day.js
Day.js.extend(duration);
const durationDay.js = Day.js.duration(5000); // 5 seconds
console.log(durationDay.js.asMinutes()); // 0.083333...
const humanizedDurationDay.js = Day.js.duration(5000).humanize(); // 'a few seconds'

// Moment.js
const durationMoment = moment.duration(5000); // 5 seconds
console.log(durationMoment.asMinutes()); // 0.083333...
const humanizedDurationMoment = moment.duration(5000).humanize(); // 'a few seconds'
Enter fullscreen mode Exit fullscreen mode

Day.js vs Moment.js: A Detailed Comparison

Day.js and Moment.js are two popular libraries for date manipulation in JavaScript. While both serve the same purpose, they have distinct differences in terms of performance, features, and usability. This comparison will help you decide which library is better suited for your project.

Day.js

Pros

  • Lightweight: Day.js is only 2KB in size, significantly smaller than Moment.js, which makes it ideal for performance-sensitive applications.
  • Immutable: Day.js promotes immutability, meaning every operation returns a new instance, reducing bugs related to date manipulation.
  • Plugin Architecture: Day.js has a modular plugin system, allowing you to include only the functionality you need. This keeps your bundle size minimal.
  • Modern Syntax: Day.js follows modern JavaScript syntax, making it easier to integrate with modern codebases.
  • Compatibility: Day.js is designed to be a drop-in replacement for Moment.js, with a similar API.

Cons

  • Fewer Built-in Features: Day.js has fewer built-in features compared to Moment.js. Advanced functionality requires additional plugins.
  • Limited Timezone Support: Day.js relies on third-party plugins for comprehensive timezone support, whereas Moment.js has Moment Timezone.
  • Less Mature Ecosystem: As a newer library, Day.js has fewer integrations and community support compared to the well-established Moment.js.

Moment.js

Pros

  • Feature-Rich: Moment.js provides a comprehensive set of features for almost any date and time manipulation task.
  • Mature Ecosystem: Moment.js has been around since 2011, resulting in extensive community support, plugins, and integrations.
  • Timezone Handling: Moment.js, with its Moment Timezone plugin, offers robust timezone support, making it ideal for applications that need to handle multiple time zones.
  • Detailed Documentation: Moment.js has detailed and well-maintained documentation, making it easier for developers to find help and examples.

Cons

  • Large Size: Moment.js is significantly larger than Day.js, which can impact performance, especially in client-side applications.
  • Mutable Operations: Moment.js operations mutate the original date object, which can lead to unexpected behavior if not managed carefully.
  • Deprecated: The Moment.js team has deprecated the library, recommending alternatives like Day.js for new projects.

Comparison Table

Feature Day.js Moment.js
Size ~2KB ~70KB
Immutability Yes No
Plugin Architecture Yes Limited
Feature Set Basic (extensible via plugins) Comprehensive
Timezone Support Limited (via plugins) Extensive (Moment Timezone)
Ecosystem Growing Mature
Documentation Good Extensive
Modern Syntax Yes No
API Compatibility Similar to Moment.js N/A
Status Actively maintained Deprecated

Conclusion

When working with dates in JavaScript, it’s essential to choose the right tool for the task. Native JavaScript Date objects are sufficient for basic date manipulation tasks, but for more advanced operations, libraries like Day.js and Moment.js offer powerful and convenient features.

When deciding between Day.js and Moment.js, consider the specific needs of your project.

  • Choose Day.js if you need a lightweight, modern, and immutable library with modular capabilities. It's ideal for performance-sensitive applications and projects that don't require extensive timezone handling out of the box.

  • Choose Moment.js if you need a feature-rich library with comprehensive timezone support and mature ecosystem. However, keep in mind that Moment.js is deprecated, and for new projects, it's recommended to consider alternatives like Day.js.

Ultimately, both libraries have their strengths and are suited to different types of projects. Evaluate your project's requirements carefully to make an informed decision. Try integrating these tools into your next project and experience the ease of handling dates in JavaScript.

Happy coding!

Top comments (2)

Collapse
 
duncan_true profile image
Dun

Which scenarios would you recommend using the native Date object over Day.js or Moment.js? Great comparison, by the way!

Collapse
 
syakirurahman profile image
Syakir

The first section of this article discussing the common scenarios to use native JS date