1. Code
  2. JavaScript

Using Luxon for Date and Time in JavaScript

Scroll to top

Luxon is an incredibly powerful library for working with dates and times in JavaScript. There are many features in the library that make it appealing for developers. For example, the API is simple and intuitive. The library has support for interval and duration, as well as built-in handling of time zones. It can also handle parsing and formatting of date-times, intervals, and duration.

In this tutorial, you will learn how to use the Luxon library in your projects.

Installation

One of the great things about Luxon is that you can use it on all kinds of JavaScript environments. For example, you can use it directly in your browser by loading it from a CDN.

Once you add the script tag as shown below:

1
<script src='https://cdnjs.cloudflare.com/ajax/libs/luxon/3.3.0/luxon.min.js'></script>

You will be able to run the following code in the browser:

1
let DateTime = luxon.DateTime;
2
3
// Output: 2023-06-19T09:00:00.882+05:30

4
console.log(DateTime.now().toString());

You can also install it via NPM:

1
npm install --save luxon

You will now be able to run the following code in the browser:

1
const { DateTime } = require("luxon");
2
3
// Output: 2023-06-19T09:12:08.021+05:30

4
console.log(DateTime.now().toString());

The official website explains how you can install and use the library in different environments.

Creating a DateTime Object

One of the most useful classes in Luxon is the DateTime class, which you can use to create DateTime objects. These DateTime objects represent a specific time, accurate to the millisecond. They also contain information about the time zone and the locale.

There are many ways of creating a DateTime in Luxon. Consider the following examples:

1
let DateTime = luxon.DateTime;
2
3
let localDt = DateTime.local();
4
// Output: "2023-06-19T09:30:09.710+05:30"

5
console.log(localDt.toString());
6
7
let currentDt = DateTime.now();
8
// Output: "2023-06-19T09:30:09.710+05:30"

9
console.log(currentDt.toString());
10
11
let isoDt = DateTime.fromISO("1992-12-25");
12
// Output: "1992-12-25T00:00:00.000+05:30"

13
console.log(isoDt.toString());
14
15
let objectDt = DateTime.fromObject({year: 2021, month: 5, day: 19});
16
// Output: "2021-05-19T00:00:00.000+05:30"

17
console.log(objectDt.toString());

The DateTime object itself contains a lot of information. We used the toString() method here to only get ISO 8601 format strings for our date.

The local() method can be called with or without any parameters. When no parameters are passed, it returns the current date and time. This is what happened in our example.

Another way of getting the current date and time is with the help of the now() method. Using now() is much clearer in my opinion because the method name gives an indication of what you should expect.

You can also create a DateTime object for a specific instance of time by passing an ISO 8601 string to the fromISO() method. I should mention that this isn't the only supported string format. You can also pass dates and times in SQL format to the fromSQL() method.

Similarly, the fromHTTP() method allows you to parse strings formatted according to the HTTP header specs.

Accessing Date and Time Information

Once you have created your DateTime objects, you will likely want to extract relevant information from the dates for further use. Luxon provides accessors for easy access to all the components of a date-time object.

1
let DateTime = luxon.DateTime;
2
let currentDt = DateTime.now();
3
4
// Output: "Year: 2023"

5
console.log(`Year: ${currentDt.year}`);
6
7
// Output: "Month: 6"

8
console.log(`Month: ${currentDt.month}`);
9
10
// Output: "Day: 19"

11
console.log(`Day: ${currentDt.day}`);
12
13
// Output: "Hour: 9"

14
console.log(`Hour: ${currentDt.hour}`);
15
16
// Output: "Minute: 57"

17
console.log(`Minute: ${currentDt.minute}`);
18
19
// Output: "Second: 44"

20
console.log(`Second: ${currentDt.second}`);

As you can see, Luxon provides a concise API for accessing the current year, month, day, hour, minute, or second. Compare this to the native Date object in JavaScript, which requires methods like getFullYear(), getMonth() etc.

You can also get other related information such as the short and long versions of human-readable month or weekday names. The DateTime object also provides information about the time zone, like its offset or name.

1
let currentDt = DateTime.local(2016, 2, 18, 5, 12, 36);
2
3
// Output: "Weekday Short: Thu"

4
console.log(`Weekday Short: ${currentDt.weekdayShort}`);
5
6
// Output: "Weekday Long: Thursday"

7
console.log(`Weekday Long: ${currentDt.weekdayLong}`);
8
9
// Output: "Month Short: Feb"

10
console.log(`Month Short: ${currentDt.monthShort}`);
11
12
// Output: "Month Long: February"

13
console.log(`Month Long: ${currentDt.monthLong}`);
14
15
// Output: "Time Zone Name: Asia/Calcutta"

16
console.log(`Time Zone Name: ${currentDt.zoneName}`);
17
18
// Output: "Time Zone Offset: 330"

19
console.log(`Time Zone Offset: ${currentDt.offset}`);

The time zone offset value is in minutes. So 330 means 5 hours and 30 minutes.

Adding and Subtracting a Period of Time

Before we proceed further, I would like to mention that dates in Luxon are immutable. This means that any methods that you use to manipulate dates in Luxon will result in the creation of new copies of the original object with the changes applied.

Doing math with dates is complicated because of the variation in the number of days in a year or in different months of the same year. Even the hours in a day can change due to DST, and the time is different across different time zones as well.

Luxon starts computation with the highest order first and then progresses to the lowest order. This prevents any ambiguity and confusion in the final result.

For example, consider adding a month and a day to a date like September 30. If you add the month first, the date becomes October 30. Adding a day after that makes it October 31. On the other hand, adding a day to September 30 will make it October 1. Adding a month after that will make it November 1.

Here is an example:

1
let DateTime = luxon.DateTime;
2
3
let oneDt = DateTime.local(2016, 9, 30);
4
let twoDt = oneDt.plus({months: 1, days: 1});
5
let threeDt = oneDt.plus({days: 1}).plus({months: 1});
6
7
// Output: "2016-09-30T00:00:00.000+05:30"

8
console.log(oneDt.toString());
9
10
// Output: "2016-10-31T00:00:00.000+05:30"

11
console.log(twoDt.toString());
12
13
// Output: "2016-11-01T00:00:00.000+05:30"

14
console.log(threeDt.toString());

In the above example, we used the plus() method to add a specific duration to our DateTime object. Similarly, you can subtract a period of time from your DateTime object by using the minus() method.

Here are some examples:

1
let DateTime = luxon.DateTime;
2
3
let oneDt = DateTime.local(2016, 3, 4, 12, 18, 22);
4
let twoDt = oneDt.minus({months: 12, days: 10});
5
let threeDt = oneDt.minus({days: 35});
6
7
// Output: "2016-03-04T12:18:22.000+05:30"

8
console.log(oneDt.toString());
9
10
// Output: "2015-02-22T12:18:22.000+05:30"

11
console.log(twoDt.toString());
12
13
// Output: "2016-01-29T12:18:22.000+05:30"

14
console.log(threeDt.toString());

The value of twoDt shows 2015-02-22 because subtracting 12 months from 2016-03-04 takes us to 2015-03-04. After that, subtracting 10 more days from March 4 takes us to 24 February because there are only 28 days in February in a non-leap year.

The month of March had only four days left to subtract. Therefore, we reduced the month value by 1 to get to February. Luxon takes care of any overflows like this for us.

Going to the Start and End of a Time Unit

There are methods like startOf() and endOf() which you can use to set the date and time to the beginning and end of the specified unit of time. The units you specify can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.

1
let DateTime = luxon.DateTime;
2
3
let oneDt = DateTime.local(2016, 3, 4, 12, 18, 22);
4
5
// Output: "2016-03-04T12:18:22.000+05:30"

6
console.log(oneDt.toString());
7
8
// Output: "2016-03-01T00:00:00.000+05:30"

9
console.log(oneDt.startOf('month').toString());
10
11
// Output: "2016-12-31T23:59:59.999+05:30"

12
console.log(oneDt.endOf('year').toString());
13
14
// Output: "2016-03-06T23:59:59.999+05:30"

15
console.log(oneDt.endOf('week').toString());
16
17
// Output: "2016-03-04T12:59:59.999+05:30"

18
console.log(oneDt.endOf('hour').toString());

One interesting thing to note about the startOf() method is that it sets the value of all the smaller units of time to their minimum possible value. This is because that's what technically makes it the starting point of the month.

Similarly, when we specify year as the unit for our endOf() method, the values for the month, day, hour, minute, second, and millisecond were set to their highest possible value.

Comparing Dates in Luxon

Comparing dates is easy with Luxon because it implicitly gets the epoch timestamp for the dates we are comparing using the valueOf() method. This allows us to use the comparison operators in mathematics to compare dates.

You can also use the hasSame() method to compare if two dates have the same year, the same month, or the same day. Please note that a comparison for a unit of time such as the day also compares the year and month. These three values have to match for the day to be considered the same.

Here is some code that compares dates in Luxon:

1
let DateTime = luxon.DateTime;
2
3
let past = DateTime.local(2016, 6, 4, 12, 18, 22);
4
let present = DateTime.now();
5
let future = DateTime.local(2028, 6, 24, 2, 18, 17);
6
let more_future = DateTime.local(2028, 6, 24, 12, 28, 17);
7
8
// Output: true

9
console.log(past < present);
10
11
// Output: true

12
console.log(future > present);
13
14
// Output: true

15
console.log(future.hasSame(more_future, 'day'));
16
17
// Output: false

18
console.log(past.hasSame(future, 'month'));
19

The last statement logs false because the years don't match in past and future. Luxon uses the argument that the month cannot be the same if the years don't match.

Final Thoughts

In this tutorial, I aimed to teach you the basics of the Luxon library in JavaScript. This library provides a lot of useful methods for manipulating the date and time in JavaScript. The API is easy to use, and the dates are immutable.

We began the tutorial by learning how to install the library. After that, we discussed how to create DateTime objects using different methods. We also learned addition and subtraction of a period of time from given dates. Finally, we learned how to compare two dates or their components.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.