Working with date and time can be a confusing task for developers beginning with JavaScript. In this tutorial, you’ll learn about a new JavaScript library called Luxon which makes it a breeze to work with date and time in JavaScript.
Throughout the course of this tutorial, you’ll learn about the different features of the Luxon library and how to use it in your web application projects.
Getting Started
You’ll be creating an Angular project and will see how to use the Luxon library for date and time manipulation in Angular. Let’s get started by creating an Angular web app.
ng new AngularLuxon
Once you have the project created, navigate to the project directory and create a new component called luxdate
.
ng g component luxdate
You will have the LuxdateComponent
created and added to the application module in the app.module.ts
file. Remove the default AppComponent
from the application by deleting the component files from the src/app
folder. Here is how the app.module.ts
file looks:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { LuxdateComponent } from './luxdate/luxdate.component'; @NgModule({ declarations: [ LuxdateComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [LuxdateComponent] }) export class AppModule { }
Modify the src/index.html
file to add the LuxdateComponent
.
Save the above changes and start the server.
npm start
You will have the application running at http://localhost:4200/.
Let’s import the Luxon library into your application.
npm install --save luxon
Once you have Luxon installed in the Angular application, import it in the LuxdateComponent
component. Now you are ready to use the Luxon library in your project.
Local Time & UTC Time Using Luxon
Let’s have a look at how to get the local time using the Luxon
library. Import DateTime
from the Luxon library.
import { DateTime } from 'luxon';
Inside the LuxdateComponent
, define a variable called localDatetime
.
public localDatetime;
Set the value of the localDatetime
variable as shown:
this.localDatetime = DateTime.local();
Render the localDatetime
variable in the luxdate.component.html
file.
{{localDatetime}}
Save the changes and you will have the local time displayed on the web page.
2017-12-31T15:55:12.761+05:30
The date and time displayed above is the local time with the time zone attached. You can format the date and time further to make it more intuitive.
Format the date and time to display using the below line of code.
this.localDatetime = DateTime.local().toLocaleString(DateTime.DATETIME_FULL);
Save the above line of code, and you will have the following date and time displayed.
December 31, 2017, 10:35 PM GMT+5:30
Similarly, the .utc
method in the DateTime
object gives the UTC time.
Add a new variable in the LuxdateComponent
to set the UTC time.
public utcDatetime;
Set the value of the utcDatetime
variable using the Luxon Datetime
object.
this.utcDatetime = DateTime.utc().toLocaleString(DateTime.DATETIME_FULL);
Render the utcDatetime
variable in the luxdate.component.html
file as shown:
Luxon Library
Local time : {{localDatetime}}UTC time : {{utcDatetime}}
Add the following CSS style to the luxdate.component.css
file.
.container{ text-align: center; width: 100%; } .time{ display: inline-block; } .local{ border: 1px solid #8c8282; text-align: left; background-color: burlywood; padding: 10px; } .utc{ margin-top: 30px; border: 1px solid #8c8282; text-align: left; background-color: burlywood; padding: 10px; } .label{ font-family: serif; font-size: 22px; font-style: initial; }
Save the above changes, and you will be able to view the local time and the UTC time using the Luxon library.
In order to display the local time and UTC time with seconds included, you can use DATETIME_FULL_WITH_SECONDS
. Here is how it will look:
ngOnInit() { this.localDatetime = DateTime.local().toLocaleString(DateTime.DATETIME_FULL_WITH_SECONDS); this.utcDatetime = DateTime.utc().toLocaleString(DateTime.DATETIME_FULL_WITH_SECONDS); }
Save the changes, and you will have the local time and UTC time displayed with seconds.
General Date and Time Information Using Luxon
The Luxon library provides an Info
class which helps in getting some general information regarding date and time.
When dealing with date and time, it’s quite common that you may need the list of months in a year. Using the Info
class, you can get the list of months as an array.
Import the Info
class in the luxdate.component.ts
file.
import { DateTime, Info } from 'luxon';
Declare a variable for the list of months and initialize it.
public months; constructor() { this.months = []; }
Set the month list from the Info
class.
this.months = Info.months();
Add the following HTML to the luxdate.component.html
file to display the months
variable content.
Month :
Save the above changes, and you will have the month list populated.
Similarly, using the weekdays
method gives you a list of the weekdays.
this.weeks = Info.weekdays();
Save the changes, and you will have the weekdays listed on the screen.
Luxon also provides an option to get the list of meridiems
using the meridiems
method.
this.meridians = Info.meridiems();
Modify the HTML code in the luxdate.component.html
to display the weeks
and meridians
.
Save the changes, and you will be able to view the weeks and meridians displayed.
Handling Internationalization Using Luxon
Luxon provides a Setting
class, using which you can handle Luxon’s overall behavior. Let’s set the default locale setting of Luxon to el
.
Import the Settings
class in the luxdate.component.ts
file.
import { DateTime, Settings, Info } from 'luxon';
In the constructor method of LuxdateComponent
, set the default locale as shown:
constructor() { Settings.defaultLocale = 'el'; }
Save the changes, and you will have the default locale set to el
.
Zone Info Using Luxon
The Luxon library provides an interface to get the details related to the zone of a particular DateTime
object. To use it, you need to import Zone
from the Luxon library.
import { DateTime, Settings, Info, Zone } from 'luxon';
Let’s try to use Zone on a Luxon DateTime
object. Create a local DateTime
Luxon object.
let dateObj = DateTime.local();
You can use the Zone
interface on the dateObj
to get the zone name. Add the following code to log the zone name.
console.log('Zone name is ', dateObj.zone.name);
Save the changes, and on running the app, you will be able to view the zone name logged in the browser console.
Zone name is Asia/Kolkata
Let’s try to print the zone name of a UTC DateTime object.
let utcObj = DateTime.utc(); console.log('Zone name is ', utcObj.zone.name);
The above code will print the zone name as UTC
.
Zone name is UTC
The Luxon Zone
interface provides a method to compare two timezones
. Let’s try to compare the timezone
of the DateTime
objects localObj
and utcObj
.
if(localObj.zone.equals(utcObj.zone)){ console.log('Both zones are equal'); } else{ console.log('Both zones are different'); }
As seen in the above code, you have used the zone.equals
method to compare the zones. Save the changes and try running the app, and you will have the result logged.
Both zones are different
Interval In Luxon
Interval
in Luxon is a wrapper for two DateTime
endpoints which can be manipulated using the Luxon methods. From the official documentation:
An Interval object represents a half-open interval of time, where each endpoint is a DateTime. Conceptually, it’s a container for those two endpoints, accompanied by methods for creating, parsing, interrogating, comparing, transforming, and formatting them.
There are a couple of different ways of creating an interval using Luxon. Let’s look at how to create an interval using a start and end DateTime
object.
Import Interval
from Luxon in LuxdateComponent
.
import { Interval } from 'luxon';
Create a start
DateTime
object and an end
DateTime
object.
let startDate = DateTime.local(); let endDate = DateTime.local().plus({minutes : 15});
As seen in the above code, you created the startDate
using the current local time and endDate
by incrementing the local time by 15 minutes.
Create an interval using the fromDateTimes
method.
let intv = Interval.fromDateTimes(startDate, endDate); console.log('Interval is ',intv);
Save the above changes, and on running the application, you will have the interval logged.
Now you can apply the Luxon method to manipulate or format the start and end time in the interval object. Let’s say you want to check the zone name of the start time in the interval. You can do so by using the zone.name
property as shown:
console.log('Start date zone is ',intv.s.zone.name);
You will have the following output logged in the browser console:
Start date zone is Asia/Kolkata
Creating Duration Using Luxon
Luxon provides a couple of methods to create duration. To get started with creating duration, you need to import Duration
in your LuxdateComponent
.
import { Duration } from 'luxon';
Once it’s imported, you can use the fromMillis
method to create a duration by specifying the milliseconds.
let fiveMinute = Duration.fromMillis(5 * 60 * 1000); console.log('Five minutes is ', fiveMinute);
Save the changes, and on running the application, you will have the above fiveMinute
duration logged.
You can also use another DateTime
object to create a duration using the fromObject
method. Here is how the code looks:
let startDate = DateTime.local(); let dur = Duration.fromObject(startDate); console.log('Duration from object is ', dur);
Save the changes, and you will have the duration logged in the browser console.
Wrapping It Up
In this tutorial, you saw how to get started with using the Luxon library for working with date and time in an Angular web project. You learnt how to deal with local time and UTC time, and how to create an interval and duration using Luxon.
For in-depth information on using the Luxon library, I would recommend reading the official documentation.
How was your experience learning to work with Luxon? Do let us know your thoughts in the comments below.
Powered by WPeMatico