joshxyzhimself
jxyz

Follow

jxyz

Follow
JavaScript Date & Time with Luxon

Photo by Thomas Bormans on Unsplash

JavaScript Date & Time with Luxon

joshxyzhimself's photo
joshxyzhimself
·Jul 25, 2022·

1 min read

Overview

Luxon is a JavaScript module for working with Date & Time.

Use Cases

  • Parsing date & time values (from HTTP, RFC, SQL, ISO, or custom formats)
  • Formatting date & time values (to HTTP, RFC, SQL, ISO, or custom formats)
  • Math operations, comparing date & time values

Supported Environments

  • Web Browsers (Chrome, Firefox, Edge)
  • Node.js

More info here: Docs: Support Matrix

Why Luxon

  • Instances are immutable
  • Function calls are chainable
  • Support for HTTP, RFC, SQL, ISO formats
  • Support for time-zones
  • Support for math operations

More info here: Docs: Why Luxon

Installation

npm install luxon

Usage

// CommonJS
const luxon = require('luxon');

// ECMAScript
import * as luxon from 'luxon';

// parsing:
const example = luxon.DateTime.fromISO('2022-07-25T05:37:54.000+08:00');
const example2 = luxon.DateTime.fromISO('2022-07-26T05:37:54.000+08:00');

// formatting:
console.log(example.toHTTP()); // 'Sun, 24 Jul 2022 21:37:54 GMT'
console.log(example.toRFC2822()); // 'Mon, 25 Jul 2022 05:37:54 +0800'
console.log(example.toSQL()); // '2022-07-25 05:37:54.000 +08:00'
console.log(example.toISO()); // '2022-07-25T05:37:54.000+08:00'
console.log(example.toISODate()); // '2022-07-25'

// math operations:
console.log(example > example2); // false
console.log(example < example2); // true

References