You can use JavaScript to build dynamic web applications and applications that run in other environments, including the desktop. Many apps need to handle dates and times, from schedulers and chat applications to event booking apps.

Luxon offers a superior alternative to the native JavaScript Date object, with more user-friendly, reliable ways to handle date and time operations.

Installing Luxon

You can add Luxon to your JavaScript app in several ways, depending on your preferred method. The two most common methods are to use npm to install the library or to use a CDN link to include the library in your application.

To install Luxon in a Node.js project, run the following npm command in your terminal:

        npm install --save luxon

Use the library in your JavaScript file by requiring luxon:

        const { DateTime } = require("luxon");

This code uses object destructuring to import the DateTime class from the Luxon library and create a new variable DateTime referencing that class.

This allows you to create instances of dates and times and perform operations such as formatting dates for display.

Alternatively, you can include Luxon in your application using a CDN link. To do this, add the following markup to your HTML file:

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

Using this approach, you can run scripts using Luxon in the body of your HTML.

Features of Luxon

Luxon provides many features, making it a valuable package for handling dates and times in JavaScript applications.

Comprehensive Date and Time Manipulation

Luxon offers various methods for creating, manipulating, and retrieving dates and times. Luxon simplifies tasks such as adding or subtracting durations, setting specific date/time components, and performing relative time calculations.

Formatting and Localization

Luxon's formatting options allow you to display dates and times in many formats. Luxon supports different format patterns and lets you set dates and times according to other languages.

Timezone Support

With Luxon, you can efficiently work with dates and times in different time zones. Luxon provides methods to set and convert between time zones.

Immutable Design

Luxon follows an immutable design pattern, ensuring that DateTime objects are immutable. This design approach provides predictable and consistent behavior when working with dates and times.

Extensive API Documentation

Luxon's API documentation is very detailed, making it easy to explore and understand the available methods, options, and functionality.

The DateTime Class in Luxon

The DateTime class in Luxon represents a particular date and time. It offers both class and instance methods that let you carry out various tasks. These tasks include creating, parsing, retrieving, modifying, and formatting dates and times.

Here are some of the different ways to create a new instance of the Date Time class in Luxon:

  • The DateTime.local() method:
            const dt = DateTime.local(2023, 5, 21, 1, 22, 37, 845);
    This code creates a new DateTime instance using the DateTime.local() method. The method takes seven arguments representing the year, month, day, hour, minute, second, and millisecond values of the date and time you want to create.
  • The DateTime.fromJSDate() method:
            const now = new Date();
    const dt = DateTime.fromJSDate(now);
    The code creates a new native JavaScript Date instance and passes it to the DateTime.fromJSDate() method. That method returns a DateTime object representing the same date and time.
  • The DateTime.fromObject() method:
            const dt = DateTime.fromObject({
        year: 2023,
        month: 1,
        day: 1,
        hour: 0,
        minute:0,
        second: 0,
        millisecond: 0
    });
    This code block shows how to create a new DateTime instance using the DateTime.fromObject() method. The method takes an object with properties representing the year, month, day, hour, minute, second, and millisecond values of the date and time you want to create.
  • Using the DateTime.now() method:
            const dt = DateTime.now();
    This code block shows how to create a new Date Time instance using the DateTime.now() method. The method returns a new DateTime instance representing the current date and time in the local time zone.

Formatting DateTime Objects to Strings

Luxon simplifies the formatting of DateTime objects into strings representing specific dates and times. You can use Luxon to format dates and times in various methods.

ISO 8601

The ISO 8601 format is widely used for standardized date and time representation. To format a DateTime object as an ISO 8601 string, use the toISO() method:

        const now = DateTime.local();
console.log(now.toISO()); // 2023-05-21T15:20:07.936+01:00

Human Readable Formats

Luxon supports human-readable formats that you can customize for local languages. You can format a DateTime object to a human-readable string with the toLocaleString() method:

        const now = DateTime.local();
console.log(now.toLocaleString()); // 5/21/2023

Token Based Formatting

Token-based formatting allows you to format date and time into custom strings using placeholders called tokens. To format a DateTime object using tokens, use the toFormat() method:

        const now = DateTime.local();
console.log(now.toFormat("yyyy-MM-dd HH:mm:ss")); //2023-05-21 15:16:57

In the example above, the format string yyyy-MM-dd HH:mm:ss represents the desired output format. The tokens yyyy, MM, dd, HH, mm, and ss correspond to the year, month, day, hour, minute, and second of the DateTime object, respectively.

Luxon allows you to perform a wide range of date and time representations by providing an extensive set of tokens.

Parsing and Validating Dates and Times in Luxon

Luxon provides robust methods for parsing and validating dates and times. These features are useful for tasks such as validating user input or converting string representations of dates and times into DateTime objects.

The fromFormat() Method

The fromFormat() method allows you to parse a string representation of a date and time, and converts it into a DateTime object. It takes two arguments, the input string and a format string specifying the input format.

For example:

        DateTime.fromFormat("May 25 2023", "LLLL dd yyyy")

Validating Dates and Times With the isValid Method

The isValid method checks if a DateTime object represents a valid date and time. It returns true if the object is valid and false otherwise.

Like so:

        const invalidDate = DateTime.fromObject({ year: 2022, month: 2, day: 29 });
console.log(invalidDate.isValid); // false

const validDate = DateTime.fromObject({ year: 2022, month: 2, day: 28 });
console.log(validDate.isValid); // true

In the example, the first DateTime object represents an invalid date because February 29, 2022, is not valid. The second DateTime object represents a valid date of February 28, 2022.

Parsing and validation features in Luxon help you accurately handle dates and times, validate inputs, and provide reliable representations of date and time data.

Alternatives to Luxon

You have learned how to create, format, and validate date and time instances with Luxon. These tips will assist you when building web apps that require date and time handling.

You can also utilize other JavaScript packages to achieve date and time handling in your web applications, including Day.js and Date.fns. These packages have their advantages and disadvantages, and you should base your preference on your specific needs.