JavaScript Dates - How to Use Day.js for Date Handling
Day.js is a lightweight JavaScript library for parsing, validating, manipulating, and displaying dates and times. It's known for its simplicity and bundle size.
Dates drive most JS developers crazy at some point in their career, so it's always nice to have a reliable library that's easy to use.
In this short article, I'll go over some of the basics and more advanced topics in Day.js so you can see it in action and start using it in your projects:
Installation
First, you need to install Day.js in your project. You can do this using npm or yarn:
npm install dayjs // or yarn add dayjs
After installation, import Day.js into your JavaScript file:
import dayjs from 'dayjs';
For other options like the browser, check out the docs here.
Quick Note: Immutability
Unlike JavaScript's native Date object, Day.js handles dates immutably. When you modify a Day.js date, it returns a new instance, leaving the original unchanged. This feature enhances predictability and debugging in your applications.
This is very handy for creating predictable, testable code!
Code Time!
Date Arithmetic
Day.js makes it easy to perform date arithmetic, such as adding or subtracting days, months, or years. For instance, to add 14 days and subtract 3 years from the current date:
const now = dayjs(); // `now` is a timestamp e.g. "2021-01-04T14:19:24.908Z" const futureDate = now.add(14, 'day'); const pastDate = now.subtract(3, 'year');
Date Parts
You can extract parts of a date like year, month, day, etc.:
const now = dayjs(); const year = now.year(); const month = now.month(); // Note: Month is 0-indexed const day = now.date();
Date Formatting
Day.js allows for flexible date formatting. For example:
const now = dayjs(); const formatted = now.format('YYYY-MM-DD'); // Assuming timestamp is "2024-01-04T14:24:02.782Z" // Formatted looks like this: "2024-01-04"
It is super flexible so I'd recommend diving into the docs if you are struggling with your formatting needs.
You can find the formatting section right here.
Practical Examples
Here are some very common use cases I've used Day.js for:
Calculating Time Since an Event
For example, calculating the number of days since a historical event:
const eventDate = dayjs('1812-09-07'); const daysSinceEvent = dayjs().diff(eventDate, 'days');
Working with Time Zones
Using Day.js, you can easily handle different time zones:
const customDayjs = dayjs().tz('America/New_York');
Validating Dates
To check the validity of a date:
const validDate = dayjs('2020-01-01'); const invalidDate = dayjs('invalid-date-string'); console.log(validDate.isValid()); // true console.log(invalidDate.isValid()); // false
For more detailed examples and explanations, you can refer to the Day.js documentation, and these are two of the best articles I found on the topic:
Happy coding! 🙌