Introduction to Luxon
Luxon is a powerful JavaScript library for working with dates and times. It offers a comprehensive and easy-to-use API for parsing, formatting, and manipulating date and time values.
Creating Dates
You can create dates in Luxon using various methods:
const now = luxon.DateTime.now(); const specificDate = luxon.DateTime.fromISO('2021-04-30T10:20:30'); const fromObject = luxon.DateTime.fromObject({ year: 2021, month: 4, day: 30, hour: 10, minute: 20, second: 30 });
Formatting Dates
Luxon offers powerful date formatting capabilities.
const formatted = now.toFormat('yyyy LLL dd'); const localeFormatted = now.setLocale('fr').toLocaleString(luxon.DateTime.DATE_FULL);
Date Math
You can easily perform date math with Luxon:
const plusDays = now.plus({ days: 5 }); const minusHours = now.minus({ hours: 3 });
Time Zones
Luxon makes working with time zones straightforward:
const inZone = now.setZone('America/New_York'); const diff = inZone.diff(now, 'hours');
Duration
You can work with durations and intervals in Luxon:
const dur = luxon.Duration.fromObject({ hours: 2, minutes: 30 }); const later = now.plus(dur); const interval = luxon.Interval.fromDateTimes(now, later);
Example Application
Here’s a simple application example showcasing the use of Luxon APIs:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Luxon Example App</title> <script src="https://moment.github.io/luxon/global/luxon.min.js"></script> </head> <body> <h1>Luxon Example App</h1> <script> const now = luxon.DateTime.now(); document.body.innerHTML += `<p>Current Date and Time: ${now.toString()}</p>`; const inOneWeek = now.plus({ weeks: 1 }); document.body.innerHTML += `<p>Date and Time in One Week: ${inOneWeek.toString()}</p>`; const duration = luxon.Duration.fromObject({ days: 7 }); const futureDate = now.plus(duration); document.body.innerHTML += `<p>Future Date (7 Days Later): ${futureDate.toString()}</p>`; </script> </body> </html>
Luxon is an excellent library for handling date and time in JavaScript, making your development process much more manageable. Its clear and consistent API makes it an ideal choice for any project requiring date and time manipulation.
Hash: 064cfb74420d2d573b05e14ad58792dd35c2504eb652bf069621854d4f7f2ba6