Luxon

This YouTube video was created by Steve Griffith.

The Luxon library provides a powerful and friendly wrapper for the JavaScript Date object. Luxon makes it easier to parse and format dates, calculate durations, and provide time zones and international support.

Installing Luxon

Luxon can be added to an existing project using a CDN.

<script src="https://cdn.jsdelivr.net/npm/luxon@1.25.0/build/global/luxon.min.js"></script>

Once the Luxon library has been added, we will have access to all the Luxon data objects including: DateTime, Duration, Info and Interval.

Accessing DateTime

The DateTime object can be accessed through the Luxon object. Many developers find it more convenient to add a shortcut to the DateTime object by creating a DateTime variable.

const DateTime = luxon.DateTime

From the short any of Luxon's DateTime properties and methods are accessible.

const DateTime = luxon.DateTime
const now = DateTime.local() // current date and time

Creating a DateTime

Using Luxon, a DateTime can be created from a string, an object, or a list of parts. Each requires a different method.

local

The DateTime.local() method takes a number of arguments representing the different parts of DateTime from years to milliseconds.

const DateTime = luxon.DateTime

// create a date for November 1, 2020 at 10:30
const date = DateTime.local(2020, 11, 1, 10, 30)

The arguments must be placed in a specific order (year, month, day, hour, minute, second, millisecond). Each argument is optional and has a default value. If no arguments are provided the current date and time are returned.

fromObject

A more powerful way to create a DateTime is to use the DateTime.fromObject() method. The fromObject() method will take an object that can contain not only the standard DateTime components used by the local() method but also other aspects including the time zone and the international locale.

const DateTime = luxon.DateTime

// create a date for November 1, 2020 at 10:30
const date = DateTime.local({ year: 2020, month: 11, day: 1, hour: 10, minute: 30})

fromISO

The DateTime.fromISO() method can parse ISO 8601, which is one of the most common formats from dates and times.