DEV Community

Vishal Singh
Vishal Singh

Posted on

Managing Dates, Times and Time Zone Using Moment.js

Working with dates and times in JavaScript has always been a bit complex. That’s why if you ask a date-related question on StackOverflow, you’ll often hear the reply “Use Moment.js”.

What Is Moment.js?

Moment.js is big open source community working with dates and times in JavaScript. It allows you to parse, validate, manipulate, and display dates and times using a clean and concise API.

In this blog I’ll show you how to get up and running with Moment.js, as well as demonstrate several of its common use cases.

Getting Started with Moment.js

Moment.js can be run from the browser as well as from within a Node application. In order to use it with Node, install the module using the anyone following command.

npm install moment

yarn add moment
Enter fullscreen mode Exit fullscreen mode

Then, simply require() or import and use it in your application as shown below.

const moment = require('moment') or import moment from 'moment';
const today = moment();
console.log(today.format());

// 2023-05-05T10:55:16+05:30
Enter fullscreen mode Exit fullscreen mode

Date Formatting

Moment.js has simplified the process of date conversion to any particular format. Date format conversion with Moment is simple, as shown in the following example.

moment().format('MMMM Do YYYY, h:mm:ss a'); // May 5th 2023, 11:04:44 am
moment().format('dddd');                    // Friday
moment().format("MMM Do YY");               // May 5th 23
moment().format('YYYY [escaped] YYYY');     // 2023 escaped 2023
moment().format();   // 2023-05-05T10:55:16+05:30                     
Enter fullscreen mode Exit fullscreen mode

Manipulating Dates

There are a number of options for manipulating the moment object. For example, you can add or subtract days, months, years, etc. This is achieved via the add() and subtract() methods. The following example shows how seven days, months, or weeks are added to the current date.

moment().add(7, 'days');    // adds 7 days to current date
moment().add(7, 'months');  // adds 7 months to current date
moment().add(7, 'years');   // adds 7 years to current date
Enter fullscreen mode Exit fullscreen mode

Similarly, the subtract() method is shown below.

moment().subtract(7, 'days');   // subtracts 7 days to current date
moment().subtract(7, 'months'); // subtracts 7 months to current date
moment().subtract(7, 'years');  // subtracts 7 years to current date
Enter fullscreen mode Exit fullscreen mode

Note that each of the above examples will return the moment object. If you want a human-readable date, you’ll need to format it accordingly.

Time From Now

Another common task is determining how much time exists between two dates. For calculating time from the current date, Moment.js uses a method named fromNow().

moment('2023.05.03', 'YYYY.MM.DD').fromNow() // 2 days ago
Enter fullscreen mode Exit fullscreen mode

If we pass in true as an argument, we can get the value without the suffix.

moment('2023.05.03', 'YYYY.MM.DD').fromNow(true) // 2 days 
Enter fullscreen mode Exit fullscreen mode

International Language Support

Moment.js offers great i18n support. It allows you to assign a global language or set the language for a particular moment object. By default, it supports the English language. If you want to support any other language, then assign the key values of that particular language to moment.locale. The following abridged example, taken from the Moment.js docs, shows how support can be added for French.

import moment from 'moment';

moment.locale('fr', {
  months : 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'),
  weekdays : 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),
  relativeTime : {
      future : 'dans %s',
      past : 'il y a %s',
      s : 'quelques secondes',
      m : 'une minute',
      mm : '%d minutes',
      h : 'une heure',
      hh : '%d heures',
      d : 'un jour',
      dd : '%d jours',
      M : 'un mois',
      MM : '%d mois',
      y : 'un an',
      yy : '%d ans'
  }
});

moment.locale('fr');

moment(1316116057189).fromNow(); // il y a une heure
moment.locale('en');
moment(1316116057189).fromNow(); // an hour ago
Enter fullscreen mode Exit fullscreen mode

Moment Timezone

Moment-Timezone is an add-on for Moment.js. It can parse and display dates in any timezone. In order to use it, install the module using the anyone following command.

npm install moment-timezone --save   # npm
yarn add moment-timezone             # Yarn
Enter fullscreen mode Exit fullscreen mode

Format Dates in Any Timezone

var jun = moment("2014-06-01T12:00:00Z");
var dec = moment("2014-12-01T12:00:00Z");

jun.tz('America/Los_Angeles').format('ha z');  // 5am PDT
dec.tz('America/Los_Angeles').format('ha z');  // 4am PST

jun.tz('America/New_York').format('ha z');     // 8am EDT
dec.tz('America/New_York').format('ha z');     // 7am EST

jun.tz('Asia/Tokyo').format('ha z');           // 9pm JST
dec.tz('Asia/Tokyo').format('ha z');           // 9pm JST

jun.tz('Australia/Sydney').format('ha z');     // 10pm EST
dec.tz('Australia/Sydney').format('ha z');     // 11pm EST
Enter fullscreen mode Exit fullscreen mode

Convert Dates Between Timezones

var newYork    = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london     = newYork.clone().tz("Europe/London");

newYork.format();    // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format();     // 2014-06-01T17:00:00+01:00
Enter fullscreen mode Exit fullscreen mode

Conclusion

Moment.js is really an awesome library that simplifies date and time-related manipulations and validations. In this article, we focused on some of the features of Moment.js which help in parsing, validating, and manipulating dates and times in the browser and Node.js applications. A number of useful plugins are also available for Moment.js. For more on Moment.js, the reader is directed to the library’s documentation.

Thanks for reading this post, I hope you found it interesting!

Top comments (8)

Collapse
 
supportic profile image
Supportic

Don't use moment. It's deprecated. Use date-fns github.com/date-fns/date-fns

Collapse
 
sentientmachin3 profile image
Davide Bianchi

Moment.js is not in its best spot rn, momentjs.com/docs/#/-project-status/

Collapse
 
adriangoe profile image
Adrian Görisch

Moment js is no longer supported and should not be recommended any more.
Use day js or so as an modern alternative

Collapse
 
amatzen profile image
Alexander Matzen

I would certainly recommend Luxon. It's built by the Moment team with a more modern API to date manipulation.

DayJS is simply just moment with updates and utilizes the legacy API, that Moment is in deprecation state for.

Collapse
 
royrao profile image
Roy

It would be a better idea to use Day.js instead of moment.js.

Collapse
 
raaynaldo profile image
Raynaldo Sutisna

Day.js is a good substitution for moment.js because of similar syntax. However, if you prefer smaller packages, you may consider date-fns

Collapse
 
ashcript profile image
As Manjaka Josvah • Edited

Very helpful tip 😉 thank you

Collapse
 
singhvishal802 profile image
Vishal Singh

Thanks!