DEV Community

Matt Williams for Tech Dev Blog

Posted on • Originally published at techdevblog.io on

Effortlessly handle dates and times in JavaScript with Luxon

Introduction

Effortlessly handle dates and times in JavaScript with Luxon

Luxon is a powerful and lightweight JavaScript library for working with dates and times. It was created as an alternative to the popular Moment.js library, with the goal of being faster, smaller, and easier to use.

One of the key benefits of Luxon is its strong support for the Internationalization (i18n) features of the ECMAScript Internationalization API, which allows for formatting and parsing dates and times in a variety of languages and locales.

Luxon also has a number of other useful features, including support for time zones, duration manipulation, and calculations.

Installation

To use Luxon in your project, you can install it using npm:

npm install luxon
Enter fullscreen mode Exit fullscreen mode

Alternatively, you can download the latest version from the GitHub releases page and include it in your project manually (but you really shouldn't)

Once you have Luxon installed, you can use it in your JavaScript code by importing it:

import { DateTime } from 'luxon';
Enter fullscreen mode Exit fullscreen mode

Dates and times

One of the main features of Luxon is the DateTime class, which represents a specific point in time. You can create a DateTime object by calling the DateTime constructor and passing in a date and time as arguments:

const date = DateTime.fromISO('2022-01-01T00:00:00Z');
console.log(date); // 2022-01-01T00:00:00.000Z
Enter fullscreen mode Exit fullscreen mode

You can also create a DateTime object using the current date and time by calling the local() static method:

const now = DateTime.local();
console.log(now); // 2022-01-01T00:00:00.000-05:00
Enter fullscreen mode Exit fullscreen mode

Note that the local() method returns a DateTime object in the local time zone of the machine running the code. If you want to create a DateTime object in a specific time zone, you can use the fromObject() static method and pass in a configuration object with the desired time zone:

const date = DateTime.fromObject({
  zone: 'America/New_York',
});
console.log(date); // 2022-01-01T00:00:00.000-05:00
Enter fullscreen mode Exit fullscreen mode

Formatting and parsing

Formatting

Once you have a DateTime object, you can use its toFormat() method to convert it to a string representation in a specific format. The method takes a string argument that specifies the format using a combination of letters and symbols. For example, to format a date as a full date and time in the ISO 8601 format, you can use the following code:

const date = DateTime.fromObject({
  zone: 'America/New_York',
});

console.log(date.toISO()); // 2022-01-01T00:00:00.000-05:00
Enter fullscreen mode Exit fullscreen mode

Or you can specify a custom format:

const formatted = date.toFormat('yyyy-MM-dd HH:mm:ss');
console.log(formatted); // 2022-01-01 00:00:00
Enter fullscreen mode Exit fullscreen mode

You can also use the toLocaleString() method to format a DateTime object according to the conventions of a specific locale. For example, to format a date as a full date and time in the English (United States) locale, you can use the following code:

const formatted = date.toLocaleString(DateTime.DATE_FULL);
console.log(formatted); // Saturday, January 1, 2022
Enter fullscreen mode Exit fullscreen mode

Parsing

In addition to formatting dates and times, Luxon also provides tools for parsing them. You can use the fromFormat() static method to parse a string representation of a date and time into a DateTime object. For example, to parse a date in the ISO 8601 format, you can use the following code:

const date = DateTime.fromFormat('2022-01-01T00:00:00Z', 'yyyy-MM-ddTHH:mm:ssZ');
console.log(date); // 2022-01-01T00:00:00.000Z
Enter fullscreen mode Exit fullscreen mode

You can also use the fromISO() static method to parse a string representation of a date and time in the ISO 8601 format. This method is faster than fromFormat() and is recommended for parsing dates in this format.

const date = DateTime.fromISO('2022-01-01T00:00:00Z');
console.log(date); // 2022-01-01T00:00:00.000Z
Enter fullscreen mode Exit fullscreen mode

Time zones

Luxon has strong support for time zones and allows you to work with dates and times in any time zone. When you create a DateTime object, you can specify the time zone using the zone option. For example, to create a DateTime object in the Pacific Standard Time (PST) time zone, you can use the following code:

const date = DateTime.fromObject({
  zone: 'America/Los_Angeles',
});
console.log(date); // 2022-01-01T00:00:00.000-08:00
Enter fullscreen mode Exit fullscreen mode

You can also use the setZone() method to change the time zone of an existing DateTime object. This method returns a new DateTime object with the same point in time, but in the specified time zone:

const date = DateTime.fromObject({
  zone: 'America/Los_Angeles',
});
const newDate = date.setZone('America/New_York');
console.log(newDate); // 2022-01-01T03:00:00.000-05:00
Enter fullscreen mode Exit fullscreen mode

Durations

In addition to working with dates and times, Luxon also provides tools for working with durations. A duration is a period of time, represented as a number of days, hours, minutes, seconds, and milliseconds.

You can create a duration object using the Duration constructor and passing in an object with the desired values:

const duration = Duration.fromObject({
  days: 1,
  hours: 2,
  minutes: 30,
  seconds: 45,
  milliseconds: 123,
});
console.log(duration); // 1.11:30:45.123
Enter fullscreen mode Exit fullscreen mode

You can also create a duration object by specifying the total number of milliseconds using the of method:

const duration = Duration.of('milliseconds', 1000);
console.log(duration); // 0.00:00:01
Enter fullscreen mode Exit fullscreen mode

Once you have a duration object, you can use its toFormat() method to convert it to a string representation in a specific format. The method takes a string argument that specifies the format using a combination of letters and symbols. For example, to format a duration as a number of days, hours, minutes, and seconds, you can use the following code:

const formatted = duration.toFormat('d:hh:mm:ss');
console.log(formatted); // 1:02:30:45
Enter fullscreen mode Exit fullscreen mode

You can also use the toObject() method to convert a duration to an object with the individual values for days, hours, minutes, seconds, and milliseconds:

const obj = duration.toObject();
console.log(obj); // { days: 1, hours: 2, minutes: 30, seconds: 45, milliseconds: 123 }
Enter fullscreen mode Exit fullscreen mode

Calculations

Luxon provides a number of methods for performing calculations with dates and times. For example, you can use the plus() method to add a duration to a DateTime object and get a new DateTime object representing the resulting date and time:

const date = DateTime.fromISO('2022-01-01T00:00:00Z');
const duration = Duration.fromObject({ days: 1 });
const newDate = date.plus(duration);
console.log(newDate); // 2022-01-02T00:00:00.000Z
Enter fullscreen mode Exit fullscreen mode

You can also use the minus() method to subtract a duration from a DateTime object and get a new DateTime object representing the resulting date and time:

const date = DateTime.fromISO('2022-01-01T00:00:00Z');
const duration = Duration.fromObject({ days: 1 });
const newDate = date.minus(duration);
console.log(newDate); // 2021-12-31T00:00:00.000Z
Enter fullscreen mode Exit fullscreen mode

In addition to adding and subtracting durations, you can also use the diff() method to calculate the difference between two DateTime objects and get a duration object representing the result. For example, to calculate the difference between two dates in days, you can use the following code:

const date1 = DateTime.fromISO('2022-01-01T00:00:00Z');
const date2 = DateTime.fromISO('2022-01-03T00:00:00Z');
const duration = date1.diff(date2, 'days');
console.log(duration); // 2
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this tutorial, we have covered the main features of the Luxon JavaScript library for working with dates and times. We have seen how to create and format DateTime objects, how to work with time zones and durations, and how to perform calculations with dates and times.

Luxon is a powerful and easy-to-use library that can greatly simplify your work with dates and times in JavaScript. Whether you need to format dates and times for display, parse dates and times from strings, or perform calculations with dates and times, Luxon has you covered.

I hope this tutorial has been helpful in getting you started with Luxon. If you have any questions or comments, don't hesitate to reach out. Happy coding!

Top comments (0)