Luxon.js is the modern replacement of Moment.js
Photo by Waldemar Brandt on Unsplash
Anyone who has worked with JavaScript’s native Date method knows the limitations and the frustration it comes with. Anything beyond basic formatting and operations is cumbersome with the native Date object.
Therefore, most developers prefer other libraries for Date and Time operations. One such widely used library is Moment.js however, there is a better library that not many of us know or use.
Luxon.js is a JavaScript library built by one of the Moment.js developers to overcome the drawbacks of the Moment.js package. Since it is built by the same developers, you may find a lot of similarities between the two.
Although I won’t be diving deep since this article is geared towards the installation and usage of Luxon with vanilla JavaScript, some perks of using Luxon over Moment are listed below:-
Luxon is Immutable(can’t be mutated or changed)
Better timezone support
Explicit API
Installation
Installing Luxon.js is very straightforward. There are mainly 3 ways to install and get started with Luxon.js:
Load manually- You can install download full Luxon.js from here and just include the Luxon.js script tag like this
<script src=”luxon.js”></script>
.NPM- Luxon.js supports Node 6+ and by running
npm install — save luxon
you can quickly install it. You have to refer to it byconst { DateTime } = require(“luxon”);
in your JavaScript file.CDN- This is the method that I would be using in this article. You can grab the latest CDN from here and simply paste the HTML in between the head tags of your main index.html file.
It is worth noting that to support IE 10 or 11, you need to add the following lines to your HTML head section as well:
<script src="https://cdn.polyfill.io/v3/polyfill.js?features=default,String.prototype.repeat,Array.prototype.find,Array.prototype.findIndex,Math.trunc,Math.sign,Object.is"></script>
Getting Started
As I have stated before, I will use CDN to install Luxon.js. Therefore, I need to add the following lines to my HTML file:
<script src="https://cdn.jsdelivr.net/npm/luxon@1.25.0/build/global/luxon.min.js"></script>
That’s really all we need to get started.
We can now use all the functions and tools that Luxon offers. To keep things simple, I would not be using an external JS file instead I will write the code in our HTML files itself.
var DateTime = luxon.DateTime; //--> Luxon's date object
var localTime=DateTime.local(); // --> To get the current time
console.log(localTime.toString()) // --> Returns String ->2020-10-21T03:27:22.247+05:30
DateTime.local takes any number of arguments, all the way out to milliseconds. Underneath, this is just a Javascript Date object.
Here is what our HTML file looks like right now:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Luxon Demo</title>
<link rel="stylesheet" href="./style.css"/>
<script src="https://cdn.jsdelivr.net/npm/luxon@1.25.0/build/global/luxon.min.js"></script>
</head>
<body>
<div id="time"></div>
</body>
<script>
var DateTime = luxon.DateTime;
var localTime=DateTime.local();
console.log(localTime.toString());
</script>
</html>
Formatting DateTime
Luxon offers lots of tools for making date and time human-readable, but two of them are most important. If you want to format a human-readable string, use toLocaleString
:
var dt= luxon.DateTime().local()
dt.toLocaleString() //=> '9/14/2017'
dt.toLocaleString(DateTime.DATETIME_MED) //=> 'September 14, 3:21 AM'
This works well across different locales by letting the browser figure out what order the different parts go in and how to punctuate them.
However, if you want the string read by another program or if you want to store it in a database, you may want to use toISO
:
dt.toISO() //=> '2017-09-14T03:21:47.070-04:00'
Custom formats are also supported. Official documents provide details on further formatting.
Math operations
Luxon makes it very easy to perform math operations on date and time. Deducting or adding days and hours are some of the operations that Luxon.js supports.
Below is a code snippet that demonstrates the addition and minus operations.
var DateTime= luxon.DateTime()
var dt = DateTime.local();
dt.plus({hours:45, minutes: 23});
dt.minus({days: 9});
dt.startOf('day');
dt.endOf('hour');
As you can see, the methods minus
andplus
need a JSON object as an argument.
Intl
One of the main areas where Luxon shines is its support for Intl capabilities. Some of the most important ones are in formatting:
var dt = DateTime.local();
var f = {month: 'long', day: 'numeric'};
dt.setLocale('fr').toLocaleString(f) //=> '14 septembre'
dt.setLocale('en-GB').toLocaleString(f) //=> '14 September'
dt.setLocale('en-US').toLocaleString(f) //=> 'September 14'
Luxon’s Info class can be used to list date and time from various locales:
Info.months('long', {locale: 'fr'}) //=> [ 'janvier', 'février', 'mars', 'avril', ... ]
Durations
Many times we need to store the duration of a session or a story. Luxon provides a Duration class that can be used to represent time in a very accessible manner. You create them like this:
var dur = Duration.fromObject({hours: 2, minutes: 7});
Additionally, you can use these duration objects to add or subtract from DateTime objects as well as shown below.
dt.plus(dur);
Luxon provides various getters by default. This makes it very easy to access the data stored in these Duration objects. Some of the getters are listed below:
dur.hours //=> 2
dur.minutes //=> 7
dur.seconds //=> 0
dur.as('seconds') //=> 7620
dur.toObject() //=> { hours: 2, minutes: 7 }
dur.toISO() //=> 'PT2H7M'
I have stated some of the major and most commonly used functions. You can find all the resources and much more on this topic in their official Duration API docs.
Calendars
Luxon has fabulous support for non-standard calendars as well.
As per their official documentation, Luxon has full support for Gregorian and ISO Week calendars. In layman’s term, Luxon can parse dates specified in those calendars, format dates into strings using those calendars, transform dates using the units of those calendars, and much more.
For instance, here is Luxon working directly with an ISO calendar:
DateTime.fromISO('2017-W23-3').plus({ weeks: 1, days: 2 }).toISOWeekDate(); //=> '2017-W24-5'
Although, it is worth mentioning that using non-stand calendars is a pretty rare scenario but it is still nice to know that Luxon has support for wide standards of the calendar.
Time zones
Luxon supports different time zones. As usual, the official documentation has a whole big section about it. Users can access your data from anywhere around the globe, thus it becomes imperative to show the time in their local time zone for enhanced user experience.
You can create DateTimes in specific zones and change their zones:
DateTime.fromObject({zone: 'America/Los_Angeles'}) // now, but expressed in LA's local time
DateTime.local().setZone('America/Los_Angeles') // same
Luxon also supports UTC directly:
DateTime.utc(2017, 5, 15);
DateTime.utc();
DateTime.local().toUTC();
DateTime.utc().toLocal();
Validity Checks
One of my favorite features of Luxon is its ability to validate Date and time. It is very common to get inputs like “September 45th” while using calendars. However, Luxon acknowledges these errors and marks them accordingly.
It provides a isValid
method to check if the date is valid or not.
var dt = DateTime.fromObject({ month: 2, day: 400 });
dt.isValid //=> false
dt.toString(); //=> 'Invalid DateTime'
Converting an invalid DateTime object returns a clear error ‘Invalid DateTime’ which can come quite handy while showing error logs to users.
Conclusion
Luxon.js is an exciting yet simple DateTime library. It surely overcomes every drawback of the native DateTime object of JavaScript while providing vital support for common and everyday use cases such as TimeZones and Durations.
Luxon.js can be rightfully considered as a modern, sleek replacement for Moment.js. It borrows a lot of ideas and concepts from Moment.js and builds on it.
However, although one would find many similarities between the two packages, Luxon has some subtle differences such as Luxon methods often take option objects as their last parameter. You can find the full list of differences on their official site.
As for future support, the developers have claimed to support it indefinitely. But even the current version of Luxon is a fully-fledged alternative to Moment.js.
It is definitely worth using Luxon over Moment.js in your next project.