Managing Dates, Times and Time Zone Using Moment.js
Tags: webdev, javascript, react, development
Published: 2023-05-05 06:07:47

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
```

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
```


## 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                     
```


## 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
```

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
```

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
```
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 
```


## 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
```


## 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
```


### 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
```


### 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
```


## 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.](https://momentjs.com/)

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