Tillitsdone
down Scroll to discover

Format Dates and Times with Day.js in Node.js

Learn how to effectively handle date and time formatting in Node.js using Day.js.

Discover practical examples for timezone handling, relative time formatting, and date manipulation techniques.
thumbnail

How to Format Dates and Times with Day.js in Node.js

Stunning abstract fluid art representing time flow dynamic swirls of bright turquoise blue and emerald green creating a sense of motion and progression overhead camera angle capturing the intricate patterns high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Working with dates and times in JavaScript has always been a bit tricky. While the native Date object provides basic functionality, it often falls short when we need more advanced date manipulation and formatting. That’s where Day.js comes in – a lightweight alternative to Moment.js that makes handling dates a breeze.

Why Choose Day.js?

Day.js has become increasingly popular among Node.js developers, and for good reason. At just 2KB minified and gzipped, it’s incredibly lightweight while still providing all the essential date-handling features you need. Plus, its chainable API and familiar syntax make it a joy to use.

Abstract geometric crystalline structures in bright orange and white tones representing precision and organization macro camera angle highlighting the intricate patterns and reflections high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Getting Started with Day.js

First things first, let’s install Day.js in our Node.js project:

Terminal window
npm install dayjs

Now, let’s import it into our project:

const dayjs = require('dayjs');

Basic Date Formatting

The real power of Day.js lies in its formatting capabilities. Here are some common formatting patterns you’ll find useful:

const now = dayjs();
// Basic formatting
console.log(now.format('YYYY-MM-DD')); // 2024-11-23
console.log(now.format('DD/MM/YYYY')); // 23/11/2024
console.log(now.format('MMMM D, YYYY')); // November 23, 2024

Serene ocean waves at sunset with bright lime green water merging with golden orange horizon aerial camera angle capturing the rhythmic patterns of waves high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Working with Time Zones

One of the most powerful features of Day.js is its timezone handling. First, you’ll need to install the timezone plugin:

const utc = require('dayjs/plugin/utc');
const timezone = require('dayjs/plugin/timezone');
dayjs.extend(utc);
dayjs.extend(timezone);
// Convert between time zones
const tokyoTime = dayjs().tz('Asia/Tokyo').format('YYYY-MM-DD HH:mm:ss');

Relative Time Formatting

Want to display dates in a more human-readable format? Day.js has got you covered with its relative time feature:

const relativeTime = require('dayjs/plugin/relativeTime');
dayjs.extend(relativeTime);
const futureDate = dayjs().add(3, 'days');
console.log(futureDate.fromNow()); // in 3 days
const pastDate = dayjs().subtract(5, 'hours');
console.log(pastDate.fromNow()); // 5 hours ago

Date Manipulation Made Easy

Day.js makes it simple to perform date calculations:

// Add time
const tomorrow = dayjs().add(1, 'day');
const nextWeek = dayjs().add(1, 'week');
// Subtract time
const lastMonth = dayjs().subtract(1, 'month');
// Start/end of time periods
const startOfMonth = dayjs().startOf('month');
const endOfYear = dayjs().endOf('year');

Best Practices and Tips

  1. Always chain your operations for cleaner code
  2. Use plugins only when needed to keep your bundle size small
  3. Consider using ISO 8601 format for storing dates
  4. Remember to handle timezone conversions explicitly
  5. Use the appropriate date format for your target audience

Iridescent gem clusters in bright aqua blue and amber orange tones creating a natural abstract composition macro close-up angle highlighting the crystal formations high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

icons/logo-tid.svg

Talk with CEO

Ready to bring your web/app to life or boost your team with expert Thai developers?
Contact us today to discuss your needs, and let’s create tailored solutions to achieve your goals. We’re here to help at every step!
🖐️ Contact us
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.