Tillitsdone
down Scroll to discover

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

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

Master basic formatting, time zones, relative time, and best practices for your Node.js applications.
thumbnail

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

A minimalist abstract composition of geometric clock shapes floating in space featuring bright neon yellow and electric blue gradients against a deep black background shot from a low angle perspective looking up 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 built-in Date object provides basic functionality, it often falls short when we need more complex date manipulations. That’s where Moment.js comes to the rescue! In this guide, I’ll show you how to handle dates and times like a pro in your Node.js applications.

Getting Started with Moment.js

First things first, let’s get Moment.js installed in your Node.js project. Open your terminal and run:

Terminal window
npm install moment

Then, import it into your project:

const moment = require('moment');

An abstract representation of time flow using spiral patterns and flowing lines dominated by bright turquoise and golden yellow colors captured from a bird's eye view perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Basic Date Formatting

One of the things I love most about Moment.js is how intuitive it makes date formatting. Here are some common formatting patterns I use regularly:

const now = moment();
// Basic formatting
console.log(now.format('MMMM Do YYYY')); // September 23rd 2024
console.log(now.format('MM/DD/YYYY')); // 09/23/2024
console.log(now.format('YYYY-MM-DD')); // 2024-09-23

Working with Time

Time formatting is just as straightforward. Here’s how you can display times in various formats:

// Time formatting
console.log(now.format('h:mm:ss a')); // 3:25:50 pm
console.log(now.format('HH:mm')); // 15:25
console.log(now.format('MMMM Do YYYY, h:mm:ss a')); // September 23rd 2024, 3:25:50 pm

A dynamic abstract composition of intersecting circles and lines suggesting movement and flow of time featuring bright orange and cool teal colors against white background photographed from a diagonal perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Relative Time

One of my favorite features of Moment.js is its ability to display relative time. It’s perfect for creating user-friendly timestamps:

const futureDate = moment().add(7, 'days');
console.log(futureDate.fromNow()); // in 7 days
const pastDate = moment().subtract(3, 'hours');
console.log(pastDate.fromNow()); // 3 hours ago

Time Zone Handling

When working with international users, handling time zones properly is crucial. Moment.js makes this surprisingly simple:

// Converting to different time zones
console.log(moment().tz('America/New_York').format('LLLL'));
console.log(moment().tz('Asia/Tokyo').format('LLLL'));

Tips and Best Practices

  1. Always chain your moment methods for cleaner code
  2. Use ISO strings when storing dates in databases
  3. Parse incoming dates explicitly with a format string to avoid ambiguity
  4. Consider using moment.utc() for server-side operations

Remember, while Moment.js is incredibly powerful, it’s also quite large. For smaller projects, you might want to consider lighter alternatives like Day.js. However, when you need robust date handling capabilities, Moment.js is still an excellent choice.

An abstract landscape composition showing the passage of time through layered geometric shapes featuring vibrant lime green and concrete gray colors shot from a dramatic side angle perspective 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.