Software localization

What Is the Best JavaScript Date and Time Library?

Looking for the best JS date library or need one for formatting time? Here are 6 strong JavaScript libraries to consider for your application.
Software localization blog category featured image | Phrase

Building on our Node.js Tutorial on Creating a Multilingual Web App, this guide will help you find the JavaScript date and time library that best suits your web application. It is often a painful experience for most developers when dealing with JavaScript Date objects as it lacks the support for locale and timezone. As a result, many developers joined hand in hand and built their own modern and useful date/time libraries. It is highly recommended to use an existing library that suits your needs instead of reinventing the wheel. Let's have a detailed look at both the basics of and the differences between the following JavaScript libraries:

  • Datejs
  • Moment.js
  • Luxon
  • Dayjs
  • Date-fns
  • Spacetime

Feel free to explore them all in detail to find the Javascript date and time library that best suits your needs. At the end of the day, it is all about choosing the right tool for the right job. Let us get it started and install the necessary modules.

🔗 Resource » Check out our Ultimate Guide to JavaScript Localization for the best tips and tricks to make your JS apps ready for users across the globe.

Datejs

Datejs is an open-source JavaScript Date Library for parsing, formatting, and processing DateTime objects. It is a wrapper for the built-in JavaScript Date Constructor function with enhanced capabilities. Although the last official release was quite some time ago and has not been updated ever since, it is still a powerful library for formatting date and time. The library is suitable for those that just started learning web development. As long as you have some basic understanding of HTML and JavaScript, you are good to go with implementing it.

Installing Datejs

You can install Datejs easily by cloning the repository from the official release. Extract it in your project directory, and you are good to go.

A practical example

Within the HTML file, import the date.js located in the build folder.

<script type="text/javascript" src="build/date.js"></script>

Datejs library comes with support for more than 150 languages other than English. To change the culture, just modify the name of the js file. The following example will set the culture to German.

<script type="text/javascript" src="build/date-de-DE.js"></script>

Next, you can test it using the following syntax.

Date.today()                     // Returns today's date

Date.today().next().friday()     // Returns the date of the next Friday.

new Date().next().march()        // Returns the date of the next March.

Date.today().is().weekday()      // Is today a weekday? Return a boolean

Date.october().final().sunday()  // Returns the final Sunday in October.

Most of the function call will return an extended Date object as follows:

Function call extended Date object | Phrase

If you log it to your console, you should get the following output.

Console log | Phrase

Moment.js

Moment.js is a lightweight JavaScript date library for parsing, validating, manipulating, and formatting dates. Quite popular in the community, it gets frequent updates and has detailed documentation on how to use it.

Installing Moment.js

There are multiple ways to install the library. Feel free to choose one from one of the following.

npm install moment --save   # npm

yarn add moment             # Yarn

Install-Package Moment.js   # NuGet

spm install moment --save   # spm

meteor add momentjs:moment  # meteor

A practical example

Import the module via the following code in your JavaScript file.

const moment = require('moment');

Then, you can call it normally to format the date and time like follow:

moment().format('MMMM Do YYYY, h:mm:ss a'); // Return today's date time

moment().format('dddd');                    // Return Monday to Sunday

moment("20120620", "YYYYMMDD").fromNow();   // Return relative time based on date

moment().startOf('day').fromNow();          // Return relative time from time

moment().calendar();                        // Return calendar time

moment().add(1, 'days').calendar();         // Add a day to current calendar time

You should get the following output when you log all the output data in a list.

Date output log | Phrase

Luxon

Luxon is another library that makes it easier to work with date and time formats in JavaScript. According to the official documentation, it provides extraordinary features to add, subtract, and parse the date and time into the format you need. Although it borrows quite a lot of ideas from Moment.js, it does have its own advantages that make it stands out from Moment.js:

  • Luxon's objects are immutable while objects in Moment.js are mutable. Unlike Moment, Luxon does not require copy constructors or clone methods.
  • Moment.js uses 0-indexed for months while months in Luxon are 1-indexed.
  • Localization and timezone are implemented by the ECMAScript Internationalization API instead of by the library itself. It also comes with poly-fill support as well for older browsers.
  • Luxon has something that are not found in Moment, Duration type and an Interval type . The Interval type is like Twix.

Having said that, Luxon lacks the relative time features of Moment.js and won't provide similar support for now.

Installing Luxon

There are several ways of installation. For normal use cases, you can download the library files and include it in your HTML file as follows:

<script src="luxon.js"></script>

For Node.js users, you can install it with npm:

npm install luxon

A practical example

First and foremost, you need to create an alias for DateTime object or import the DateTime if you are using Node.js.

const DateTime = luxon.DateTime;            //alias for normal usage

const { DateTime } = require("luxon");     //import statement in Node.js

Next, you can create a new DateTime object via the following code depending on your use case:

let now = DateTime.local();

let date = DateTime.local(2017, 5, 15, 8, 30);

let dateFromObject = DateTime.fromObject({day: 22, hour: 12, zone: 'America/Los_Angeles', numberingSystem: 'beng'})

Each DateTime object has the following components or accessors:

DateTime.local().toString() // '2020-06-28T12:20:34.091+08:00'

let date = DateTime.local()

date.year     // 2020

date.month    // 6

date.day      // 28

date.second   // 34

date.weekday  // 7

Day.js

Day.js is a minimalist JavaScript library that parses, validates, manipulates, and displays dates and time. It supports most of the modern browsers and the API is similar to that of Moment.js. Nevertheless, as explained in its documentation, Day.js offers further advantages:

  • It is immutable,
  • It is a minimalist library of max. 2 KB in size,
  • Slightly faster and locales will only be included in your build when you use it.

Installing Day.js

Installation is pretty straightforward for this module. You can link it directly in your browser as follows:

<script src="https://unpkg.com/dayjs@1.8.21/dayjs.min.js"></script>

<script>dayjs().format()</script>

For Node.js users, you can easily install it via npm as shown below:

npm install dayjs

Import the module as follows:

const dayjs = require('dayjs')

A practical example

Initialization is as simple passing in a DateTime string. Besides, you can parse it from a string with specific datetime format of your choice as follow:

dayjs('2020-07-07')                // parse from string

dayjs('2020-07-07', 'YYYY-MM-DD')  // parse from string with specific format

It will return a JavaScript Object which is a little cryptic and confusing. If you want to get the result displayed, using the format function is highly recommended.

dayjs('2020-07-07')                                             // return JS Object

dayjs('2020-07-07').format()                                    // display the result as string

dayjs('2020-07-07').format('{YYYY} MM-DDTHH:mm:ss SSS [Z] A')   // display the result with specific format

The output string is as follows:

JavaScript raw DateTime string output | Phrase

Now, you can perform quite a number of operations, such as formatting, adding relative time to the object, In addition, you can query information from it as well as perform a check on it to determine whether it is before a specific date time.

dayjs('2020-07-07').add(1, 'year').format()

dayjs('2020-07-07').isBefore(dayjs())

When you log it down in your console, you should see the following output:

JavaScript formatted DateTime string output | Phrase

Day.js has good support for i18n. However, you have to load each locale manually, as shown in the code snippet below:

require('dayjs/locale/de')

dayjs.locale('de')            // use locale globally

dayjs().locale('de').format() // use locale in a specific instance

Date-fns

Date-fns is a modular DateTime JavaScript library that supports more than 70 locales and provides a simple-to-use method for manipulating JavaScript dates in your web application. You can check its official documentation here.

Installing Date-fns

Run the following command to install it via npm:

npm install date-fns

A practical example

Import it in your JavaScript file via the following code for Node.js users:

const datefns = require('date-fns');

If you are using the ES6 format, you can import just the individual components as follows:

import { format, formatDistance, formatRelative, subDays } from 'date-fns'

DateTime object manipulation can be done via the following syntax:

format(new Date(), "'Today is a' iiii")             // "Today is a Sunday"

formatDistance(subDays(new Date(), 3), new Date())  // "3 days"

formatRelative(subDays(new Date(), 3), new Date())  // "last Thursday at 5:03 p.m."

Logging the variables in a list will yield the following result:

Variable list | Phrase

For localization, locales need to be loaded manually:

const datefns = require('date-fns');

const locale = require('date-fns/locale');

datefns.formatRelative(datefns.subDays(new Date(), 3), new Date())                           // "last Friday at 3:19 p.m."

datefns.formatRelative(datefns.subDays(new Date(), 3), new Date(), { locale: locale.es })    // "el viernes pasado a las 15:19"

Spacetime

Spacetime is a lightweight JavaScript timezone library supporting daylight savings, leap years, and hemispheres. As per the official documentation, one of its most interesting features is that it takes account of quarters, seasons, months, weeks, etc.

Installing Spacetime

In order to install this module, you need to run the following command:

npm install spacetime

Then, you need to include it in your JavaScript file via the following code:

const spacetime = require('spacetime')

You can easily create a DateTime object for the present day in a single line of code.

let s = spacetime.today()

Once you have created the DateTime object, you can use the built-in functions and components based on your use case.

s.dayName()

s.season()

s.subtract(2, 'months').add(1, 'day')

s.nearest('quarter-hour')

You should get the following results when you log it to your console:

Spacetime log | Phrase

A practical example

A major advantage of Spacetime is the ability to change timezones. Let's have a look at the following example of converting the timezone to Europe/Berlin:

s = s.goto('Europe/Berlin')    // the safest way to do it via IANA Timezone name

s = s.goto('Jamaica')          // "America/Jamaica"

s = s.goto('-7h')              // UTC-7

s = s.goto('GMT+8')            // -8h

Conclusion

We hope we could help you find a JavaScript date and time library that fits your use case. Once you move on with the localization process and want to let your team translate your application into the languages of your users, consider using Phrase.

One of the most comprehensive localization solutions on the market, the Phrase Localization Suite features a flexible API and CLI, and a beautiful web platform for your translators. With GitHub, GitLab, and Bitbucket sync, Phrase does the heavy lifting in your localization pipeline, so you can stay focused on the code you love.

Check out all Phrase features for developers and see for yourself how it can help you take your apps global.