Tips and tricks for date handling with moment.js

January 31, 2018Clément Dufour2 min read

thumbnail

Handling dates when dealing with timezones is a difficult task.
Fortunately for us, there are many libraries like moment.js helping us to handle common issues like timezones, daylight saving time, manipulation and date formatting.

I recently encountered several issues in displaying dates in the correct format and timezone whilst working on a mobile application project.

An external server which sends us local date time as a string and timezone like this:

{
  localDateTime: 'YYYY-MM-DD HH:mm', // Not in UTC
  timezone: 'Indian/Reunion', // Or 'Europe/Paris''
}

I had to display and manipulate these dates. But before that, I needed to parse and store them. To be more specific with the about the use case is drawn above a diagram of the date flow in my application.

use_case

In this article, I will show you how to deal with common difficulties in date handling with one of the most standard libraries: moment.js.

What is moment ?

Moment is a very comprehensive and popular library for handling dates. It can be thought of as the standard in javascript. It provides functions to parse, manipulate and display dates and times. Moment-timezone.js adds functions to handle dates and times for different countries.

On the other hand, one should be aware that moment dates are mutable. I will deal with this issue in the manipulation part of this article.

I will focus on explaining the flow of date handling in a full JS application. I will also shed light on some tricky points of moment.

Time zone

So, what is a timezone?

Time zone is a region of the globe that observes a uniform standard time which are offset from Coordinated Universal (UTC). A time zone sets the time according to the distance from the prime meridian. Some time zones change their offset during the year. This is called daylight saving time (DST).

In the map above, you can see the time in every part on the world corresponding to the timezone without DST.

time_zone_map
Note: There is no time difference between UTC and Greenwich Mean Time (GMT). But UTC is a standard time whereas GMT is a timezone.

How to store a date

Parse the date string

When you receive a date string, you should first parse it to get the correct datetime before storing it in your database.

According to the format

Moment provides a function moment(date: string, format: string) to convert a string into a moment object according to the format.

const moment = require('moment')
C

Clément Dufour

Web Developer at Theodo