Luxon

repository·master·Indexed 9 days ago

https://github.com/moment/luxon

A modern JavaScript library for working with dates and times, built on top of the native Intl API. Luxon provides an immutable, chainable, and unambiguous API featuring core types like DateTime, Duration, and Interval. It supports native time zone and locale handling without external data files, ISO 8601 formatting, and partial support for various output calendars.

Tokens
30.4K
Snippets
85
Records
107
Agent score
93%

What's inside Luxon

  1. Introduction to Luxon

    master

    Luxon is a JavaScript library designed for working with dates and times. It provides an immutable, chainable, and unambiguous API for managing temporal data. Key features include:

    • Core Types: DateTime, Duration, and Interval.
    • Immutability: All operations return a new instance rather than mutating the existing one.
    • Native Support: Uses native time zone and Intl support, meaning it does not require external locale or time zone data files.
    • Parsing & Formatting: Supports both common and custom formats.
    DateTime.now().setZone("America/New_York").minus({ weeks: 1 }).endOf("day").toISO();
  2. What is Luxon

    master

    Luxon is a JavaScript library designed for working with dates and times. It provides a powerful API for managing complex datetime operations, including time zones, intervals, and durations.

    DateTime.now().setZone('America/New_York').minus({weeks:1}).endOf('day').toISO();
  3. Key API style differences between Luxon and Moment

    master

    Luxon's API follows different patterns than Moment.js. Note the following stylistic shifts:

    • Option Objects: Methods often accept an options object as the final parameter.
    • Explicit Creation: Instead of a single dispatcher function, Luxon uses specific static methods for different formats (e.g., DateTime.fromISO()).
    • Strict Parsing: Luxon parsers are much stricter than Moment's lenient parsers.
    • Getters vs Methods: Luxon uses property getters for access (e.g., dateTime.year) instead of method calls (e.g., dateTime.year()).
    • Centralized Setters: Instead of chaining individual setter methods, Luxon uses a centralized .set() method (e.g., dateTime.set({ year: 2016, month: 4 })).
    • Top-level Durations: Duration is a separate top-level class.
    • No Automatic Coercion: Arguments to methods are not automatically converted to Luxon instances. You must pass a Luxon object explicitly (e.g., dt.diff(DateTime.fromISO('2017-04-01')) instead of dt.diff('2017-04-01')).
  4. Compare Moment Durations and Luxon Durations

    master

    While Moment and Luxon Durations serve similar purposes, Luxon offers more sophisticated conversion capabilities.

    Key differences include:

    • Unit Conversion: Luxon can convert between different sets of units using the shiftTo method. It also allows configuration for different unit conversion logic.
    • Humanization: Luxon does not currently have a direct equivalent to Moment's .humanize() method. This feature is planned for when Intl.UnitFormat is supported by browsers.
    • Creation: Like Luxon's DateTime, Duration objects have distinct methods for creation depending on the source data.

    For detailed math and conversion logic, refer to the Duration Math documentation.

  5. Identify causes of invalid Durations and Intervals

    master

    Invalidity is not limited to DateTime objects; it also applies to Duration and Interval objects:

    • Invalid Durations: Often occur when performing operations on invalid DateTime objects (e.g., using .diffNow() on an invalid DateTime).
    • Invalid Intervals: Occur if the end time is before the start time, or if the interval was constructed using an invalid DateTime or Duration.
    // Example of an invalid Duration resulting from an invalid DateTime
    DateTime.local(2017, 28).diffNow().isValid; // false
  6. Understand time zone and offset terminology

    master

    Luxon distinguishes between several time-related concepts to manage complexity:

    • Offset: The difference between local time and UTC (e.g., +5 or -12:30).
    • Time Zone: A set of rules associated with a location (identified by an IANA string like America/New_York) that determines the offset from UTC at any given time, including Daylight Saving Time (DST) transitions.
    • Fixed-offset time zone: A zone that never changes its offset (e.g., UTC or a specific offset like UTC+7).
    • Named offset: A zone-specific name (e.g., Eastern Daylight Time). Note: Avoid using these for programmatic specification as they are ambiguous and unstandardized. Luxon only supports them for formatting purposes.
  7. How DST affects math with Days vs Hours

    master

    When performing math across Daylight Saving Time (DST) transitions, the result depends on whether you use days (Calendar math) or hours (Time math).

    • Adding Days: Luxon keeps the time of day constant. If a DST transition occurs, the actual elapsed time might be 23 or 25 hours, but the clock time remains the same.
    • Adding Hours: Luxon treats this as a fixed duration of milliseconds, which will result in the clock time shifting if a DST transition occurs.
    // Spring Forward example: adding a day keeps the hour at 10
    var start = DateTime.local(2017, 3, 11, 10);
    start.plus({days: 1}).hour;    //=> 10
    
    // Adding 24 hours (Time math) results in the hour shifting due to DST
    start.plus({hours: 24}).hour; //=> 11
  8. How missing Intl.RelativeTimeFormat affects Luxon

    master

    If the environment lacks Intl.RelativeTimeFormat support, Luxon's relative time formatting methods (like DateTime#toRelative and DateTime#toRelativeCalendar) will fall back to using English.

    FeatureFull supportNo relative time format
    Most thingsOKOK
    DateTime#toRelative in en-USOKOK
    DateTime#toRelative in other localesUses EnglishUses English
  9. Understand the difference between fully supported and output calendars

    master

    Luxon distinguishes between calendars it can perform full arithmetic on and calendars it can only use for string formatting.

    Fully Supported Calendars

    Luxon has full support for Gregorian and ISO Week calendars. This means you can:

    • Parse dates specified in these calendars.
    • Format dates into strings using these calendars.
    • Transform dates using the units of these calendars (e.g., adding weeks or days).

    Output Calendars

    Luxon has limited support for other calendaring systems (e.g., Buddhist, Chinese, Hebrew, Islamic). Support is limited to formatting strings. Luxon cannot perform calendar-specific arithmetic, such as "adding one Islamic month."

    However, you can use output calendars to show users dates in their preferred system while the underlying logic continues to use Gregorian units or Epoch milliseconds.

    // Full support example: parsing and transforming ISO Week dates
    DateTime.fromISO('2017-W23-3').plus({ weeks: 1, days: 2 }).toISOWeekDate(); //=> '2017-W24-5'
  10. Key features of Luxon

    master

    Luxon provides several core capabilities for date and time management:

    • DateTime API: A clean interface for manipulating dates and times.
    • Intervals: Support for representing a period of time between two points (from time X to time Y).
    • Durations: Support for representing a quantity of time (e.g., 14 days, 5 minutes).
    • Parsing and Formatting: Capabilities to convert strings to objects and vice versa for datetimes, intervals, and durations.
    • Internationalization: Uses the native Intl API to localize strings.
    • Time Zone Handling: Built-in support for managing different time zones.
    • Math Operations: Detailed and unambiguous mathematical operations on time objects.
    • Calendar Systems: Partial support for multiple calendar systems.
  11. Use Intervals for anchored time differences

    master

    If you need to represent a range of time that preserves the exact start and end points (to avoid the information loss associated with Duration conversions), use an Interval.

    An Interval stores its endpoints and computes its length on the fly, meaning it re-calculates the diff every time you query it, ensuring accuracy.

    • Interval.fromDateTimes(start, end): Creates an interval.
    • interval.length(unit): Returns the length of the interval in the specified unit.
    • interval.toDuration(units): Converts the interval into a Duration for a specific set of units.
    var end = DateTime.fromISO('2017-03-13');
    var start = DateTime.fromISO('2017-02-13');
    var i = Interval.fromDateTimes(start, end);
    
    // Accurate length queries
    i.length('days');       //=> 28
    i.length('months');      //=> 1
    
    // Convert to a Duration with specific units
    i.toDuration(['years', 'months', 'days']).toObject(); //=> { years: 0, months: 1, days: 0 }
  12. Transform a DateTime using immutability

    master

    Luxon DateTime objects are immutable. Methods that 'change' a date do not modify the existing instance; instead, they return a new DateTime instance.

    • Math: Use .plus({ ... }) to add time or .minus({ ... }) to subtract time. You can also use .startOf(unit) or .endOf(unit) to snap to the beginning or end of a period (e.g., 'day', 'hour').
    • Set: Use .set({ ... }) to create a new instance with specific properties overridden.
    const dt = DateTime.now();
    
    // Math returns new instances
    const later = dt.plus({ hours: 3, minutes: 2 });
    const earlier = dt.minus({ days: 7 });
    const startOfDay = dt.startOf('day');
    
    // Set returns a new instance
    const newHour = dt.set({ hour: 3 });