Lädt...


🔧 Effortlessly handle dates and times in JavaScript with Luxon


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

Introduction

Effortlessly handle dates and times in JavaScript with Luxon

Luxon is a powerful and lightweight JavaScript library for working with dates and times. It was created as an alternative to the popular Moment.js library, with the goal of being faster, smaller, and easier to use.

One of the key benefits of Luxon is its strong support for the Internationalization (i18n) features of the ECMAScript Internationalization API, which allows for formatting and parsing dates and times in a variety of languages and locales.

Luxon also has a number of other useful features, including support for time zones, duration manipulation, and calculations.

Installation

To use Luxon in your project, you can install it using npm:

npm install luxon

Alternatively, you can download the latest version from the GitHub releases page and include it in your project manually (but you really shouldn't)

Once you have Luxon installed, you can use it in your JavaScript code by importing it:

import { DateTime } from 'luxon';

Dates and times

One of the main features of Luxon is the DateTime class, which represents a specific point in time. You can create a DateTime object by calling the DateTime constructor and passing in a date and time as arguments:

const date = DateTime.fromISO('2022-01-01T00:00:00Z');
console.log(date); // 2022-01-01T00:00:00.000Z

You can also create a DateTime object using the current date and time by calling the local() static method:

const now = DateTime.local();
console.log(now); // 2022-01-01T00:00:00.000-05:00

Note that the local() method returns a DateTime object in the local time zone of the machine running the code. If you want to create a DateTime object in a specific time zone, you can use the fromObject() static method and pass in a configuration object with the desired time zone:

const date = DateTime.fromObject({
  zone: 'America/New_York',
});
console.log(date); // 2022-01-01T00:00:00.000-05:00

Formatting and parsing

Formatting

Once you have a DateTime object, you can use its toFormat() method to convert it to a string representation in a specific format. The method takes a string argument that specifies the format using a combination of letters and symbols. For example, to format a date as a full date and time in the ISO 8601 format, you can use the following code:

const date = DateTime.fromObject({
  zone: 'America/New_York',
});

console.log(date.toISO()); // 2022-01-01T00:00:00.000-05:00

Or you can specify a custom format:

const formatted = date.toFormat('yyyy-MM-dd HH:mm:ss');
console.log(formatted); // 2022-01-01 00:00:00

You can also use the toLocaleString() method to format a DateTime object according to the conventions of a specific locale. For example, to format a date as a full date and time in the English (United States) locale, you can use the following code:

const formatted = date.toLocaleString(DateTime.DATE_FULL);
console.log(formatted); // Saturday, January 1, 2022

Parsing

In addition to formatting dates and times, Luxon also provides tools for parsing them. You can use the fromFormat() static method to parse a string representation of a date and time into a DateTime object. For example, to parse a date in the ISO 8601 format, you can use the following code:

const date = DateTime.fromFormat('2022-01-01T00:00:00Z', 'yyyy-MM-ddTHH:mm:ssZ');
console.log(date); // 2022-01-01T00:00:00.000Z

You can also use the fromISO() static method to parse a string representation of a date and time in the ISO 8601 format. This method is faster than fromFormat() and is recommended for parsing dates in this format.

const date = DateTime.fromISO('2022-01-01T00:00:00Z');
console.log(date); // 2022-01-01T00:00:00.000Z

Time zones

Luxon has strong support for time zones and allows you to work with dates and times in any time zone. When you create a DateTime object, you can specify the time zone using the zone option. For example, to create a DateTime object in the Pacific Standard Time (PST) time zone, you can use the following code:

const date = DateTime.fromObject({
  zone: 'America/Los_Angeles',
});
console.log(date); // 2022-01-01T00:00:00.000-08:00

You can also use the setZone() method to change the time zone of an existing DateTime object. This method returns a new DateTime object with the same point in time, but in the specified time zone:

const date = DateTime.fromObject({
  zone: 'America/Los_Angeles',
});
const newDate = date.setZone('America/New_York');
console.log(newDate); // 2022-01-01T03:00:00.000-05:00

Durations

In addition to working with dates and times, Luxon also provides tools for working with durations. A duration is a period of time, represented as a number of days, hours, minutes, seconds, and milliseconds.

You can create a duration object using the Duration constructor and passing in an object with the desired values:

const duration = Duration.fromObject({
  days: 1,
  hours: 2,
  minutes: 30,
  seconds: 45,
  milliseconds: 123,
});
console.log(duration); // 1.11:30:45.123

You can also create a duration object by specifying the total number of milliseconds using the of method:

const duration = Duration.of('milliseconds', 1000);
console.log(duration); // 0.00:00:01

Once you have a duration object, you can use its toFormat() method to convert it to a string representation in a specific format. The method takes a string argument that specifies the format using a combination of letters and symbols. For example, to format a duration as a number of days, hours, minutes, and seconds, you can use the following code:

const formatted = duration.toFormat('d:hh:mm:ss');
console.log(formatted); // 1:02:30:45

You can also use the toObject() method to convert a duration to an object with the individual values for days, hours, minutes, seconds, and milliseconds:

const obj = duration.toObject();
console.log(obj); // { days: 1, hours: 2, minutes: 30, seconds: 45, milliseconds: 123 }

Calculations

Luxon provides a number of methods for performing calculations with dates and times. For example, you can use the plus() method to add a duration to a DateTime object and get a new DateTime object representing the resulting date and time:

const date = DateTime.fromISO('2022-01-01T00:00:00Z');
const duration = Duration.fromObject({ days: 1 });
const newDate = date.plus(duration);
console.log(newDate); // 2022-01-02T00:00:00.000Z

You can also use the minus() method to subtract a duration from a DateTime object and get a new DateTime object representing the resulting date and time:

const date = DateTime.fromISO('2022-01-01T00:00:00Z');
const duration = Duration.fromObject({ days: 1 });
const newDate = date.minus(duration);
console.log(newDate); // 2021-12-31T00:00:00.000Z

In addition to adding and subtracting durations, you can also use the diff() method to calculate the difference between two DateTime objects and get a duration object representing the result. For example, to calculate the difference between two dates in days, you can use the following code:

const date1 = DateTime.fromISO('2022-01-01T00:00:00Z');
const date2 = DateTime.fromISO('2022-01-03T00:00:00Z');
const duration = date1.diff(date2, 'days');
console.log(duration); // 2

Conclusion

In this tutorial, we have covered the main features of the Luxon JavaScript library for working with dates and times. We have seen how to create and format DateTime objects, how to work with time zones and durations, and how to perform calculations with dates and times.

Luxon is a powerful and easy-to-use library that can greatly simplify your work with dates and times in JavaScript. Whether you need to format dates and times for display, parse dates and times from strings, or perform calculations with dates and times, Luxon has you covered.

I hope this tutorial has been helpful in getting you started with Luxon. If you have any questions or comments, don't hesitate to reach out. Happy coding!

...

🔧 Effortlessly handle dates and times in JavaScript with Luxon


📈 108.61 Punkte
🔧 Programmierung

🔧 Working with Dates and Times in JavaScript


📈 35.15 Punkte
🔧 Programmierung

📰 "First Dates Hotel": So seht ihr die "First Dates"-Spin-Off-Show bei Vox


📈 32.64 Punkte
📰 IT Nachrichten

🔧 Dates, Times, and Drop-Down Lists (10 of 18) | Building Apps with XAML and .NET MAUI


📈 30.23 Punkte
🔧 Programmierung

🔧 Working with Dates and Times in SQL: Tips and Tricks


📈 30.23 Punkte
🔧 Programmierung

🔧 JavaScript Unlocked: Effortlessly Master React, Vue, and Angular


📈 28.63 Punkte
🔧 Programmierung

🪟 Anthem Demo schedule: All times and dates


📈 28.55 Punkte
🪟 Windows Tipps

🪟 Mortal Kombat 11 beta schedule: All times and dates


📈 28.55 Punkte
🪟 Windows Tipps

🔧 Handling dates and times in R: a free online course


📈 28.55 Punkte
🔧 Programmierung

📰 How to deal with dates and times without any timezone tantrums…


📈 28.55 Punkte
📰 IT Security Nachrichten

📰 How to deal with dates and times without any timezone tantrums…


📈 28.55 Punkte
📰 IT Security Nachrichten

🔧 mysql: getting a grip on dates, times, and timezones


📈 28.55 Punkte
🔧 Programmierung

📰 Displaying dates and times on Linux


📈 28.55 Punkte
📰 IT Security Nachrichten

🔧 Edge Cases in App and Backend Development — Dates & Times


📈 28.55 Punkte
🔧 Programmierung

🕵️ QEMU Handle Backend hw/9pfs/9p-handle.c Denial of Service


📈 27.26 Punkte
🕵️ Sicherheitslücken

🕵️ QEMU Handle Backend hw/9pfs/9p-handle.c Denial of Service


📈 27.26 Punkte
🕵️ Sicherheitslücken

🔧 How to Compare Two Dates in JavaScript – Techniques, Methods, and Best Practices


📈 24.59 Punkte
🔧 Programmierung

🍏 Hollywood writers' strike could lead to difficult times for Apple TV+, but Apple can handle it


📈 24.19 Punkte
🍏 iOS / Mac OS

🔧 How to Format Dates with Ordinal Number Suffixes (-st, -nd, -rd, -th) in JavaScript


📈 22.92 Punkte
🔧 Programmierung

🔧 Removing Timezones from Dates in Javascript


📈 22.92 Punkte
🔧 Programmierung

🔧 JavaScript Compare Dates: From Chaos to Clarity


📈 22.92 Punkte
🔧 Programmierung

🔧 Handling dates in JavaScript with Tempo


📈 22.92 Punkte
🔧 Programmierung

🐧 Searching through man pages for an option... quickly and effortlessly


📈 22.03 Punkte
🐧 Linux Tipps

🎥 Soft Body Wiggles And Jiggles…Effortlessly! ?


📈 22.03 Punkte
🎥 Künstliche Intelligenz Videos

📰 Qvm-Create-Windows-Qube - Spin Up New Windows Qubes Quickly, Effortlessly And Securely


📈 22.03 Punkte
📰 IT Security Nachrichten

📰 How to Check Screen Time on Android Easily and Effortlessly


📈 22.03 Punkte
🖥️ Betriebssysteme

📰 5 ways to effortlessly spot and eliminate hidden threats in your network


📈 22.03 Punkte
📰 IT Security Nachrichten

🍏 Patterns 1.3 - Build patterns quickly and effortlessly with syntax coloring.


📈 22.03 Punkte
🍏 iOS / Mac OS

🔧 Effortlessly Setting up Your React Project with Vite, Husky, TypeScript, and ESLint: A Comprehensive Guide


📈 22.03 Punkte
🔧 Programmierung

📰 How To Effortlessly Improve Data Security And Compliance Within Your Organization


📈 22.03 Punkte
📰 IT Security Nachrichten

🔧 Effortlessly Generate Structured Information with Ollama, Zod, and ModelFusion


📈 22.03 Punkte
🔧 Programmierung

matomo