Day.js

repository·dev·Indexed 10 days ago

https://github.com/iamkun/dayjs

A minimalist, 2kB immutable JavaScript library for parsing, validating, manipulating, and displaying dates and times. Designed as a modern, chainable alternative to Moment.js with a highly compatible API, it supports internationalization via on-demand locales and extensibility through a plugin system (e.g., advancedFormat, calendar, and bigIntSupport).

Tokens
17.3K
Snippets
77
Records
87
Agent score
97%

What's inside Day.js

  1. Extend Day.js functionality with Plugins

    dev

    Plugins are independent modules used to add new features or extend existing ones. To use a plugin, you must import it and then register it using dayjs.extend().

    import advancedFormat from 'dayjs/plugin/advancedFormat' // load on demand
    
    dayjs.extend(advancedFormat) // use plugin
    
    dayjs().format('Q Do k kk X x') // more available formats
  2. Use Day.js APIs to parse, manipulate, and display dates

    dev

    Day.js provides a chainable and immutable API for common date operations. Key patterns include:

    • Parsing: Create a Day.js object from a string.
    • Displaying: Format dates using template strings.
    • Getting & Setting: Retrieve or modify specific date components.
    • Manipulating: Add or subtract time units.
    • Querying: Compare dates.
    dayjs('2018-08-08') // parse
    
    dayjs().format('{YYYY} MM-DDTHH:mm:ss SSS [Z] A') // display
    
    dayjs().set('month', 3).month() // get & set
    
    dayjs().add(1, 'year') // manipulate
    
    dayjs().isBefore(dayjs()) // query
  3. Handle Internationalization (I18n) with Day.js

    dev

    Day.js supports internationalization, but locales are not included in the core bundle to keep the size small. You must load them on demand.

    • Global Locale: Set a locale for all Day.js instances using dayjs.locale().
    • Instance Locale: Set a locale for a specific instance using .locale().
    import 'dayjs/locale/es' // load on demand
    
    dayjs.locale('es') // use Spanish locale globally
    
    dayjs('2018-05-05').locale('zh-cn').format() // use Chinese Simplified locale in a specific instance
  4. Manipulate dates with Durations

    dev

    When the duration plugin is loaded, the dayjs prototype's .add() and .subtract() methods are extended to support Duration objects directly.

    If you pass a Duration instance to dayjs().add(duration), it will correctly manipulate the date by accounting for the specific units (years, months, days, etc.) within that duration.

    const dur = dayjs.duration({ months: 1, days: 5 })
    const date = dayjs('2023-01-01')
    
    const newDate = date.add(dur)
    // Result is 2023-02-06
  5. Use the relativeTime plugin

    dev

    The relativeTime plugin allows you to format dates as relative time strings (e.g., "a few seconds ago", "in 2 hours"). It adds the .fromNow(), .toNow(), .from(), and .to() methods to the Day.js instance.

    To use it, you must extend Day.js with the plugin after importing it.

    import dayjs from 'dayjs'
    import relativeTime from 'dayjs/plugin/relativeTime'
    
    dayjs.extend(relativeTime)
    
    // Examples
    dayjs().fromNow() // "a few seconds ago"
    dayjs().toNow()   // "in a few seconds"
  6. Use the isoWeek plugin

    dev

    The isoWeek plugin extends dayjs with support for ISO week calculations, including ISO week year, ISO week number, and ISO weekday. It also adds support for the isoweek unit in the .startOf() method.

    To use it, you must first extend your dayjs instance with the plugin.

    import dayjs from 'dayjs'
    import isoWeek from 'dayjs/plugin/isoWeek'
    
    dayjs.extend(isoWeek)
  7. Extend Day.js with plugins

    dev

    Day.js is designed to be lightweight. You can add functionality by using the .extend() method to install plugins.

    import dayjs from 'dayjs'
    import plugin from 'dayjs-plugin-name'
    
    dayjs.extend(plugin, { option: 'value' })
    import dayjs from 'dayjs'
    import relativeTime from 'dayjs/plugin/relativeTime'
    
    dayjs.extend(relativeTime)
    
    dayjs().fromNow()
  8. Use the quarterOfYear plugin

    dev

    The quarterOfYear plugin extends the Day.js prototype with support for quarters (Q). It allows you to retrieve the current quarter, add quarters to a date, or set a date to the start or end of a quarter.

    import dayjs from 'dayjs'
    import quarterOfYear from 'dayjs/plugin/quarterOfYear'
    
    dayjs.extend(quarterOfYear)
    
    // Get current quarter
    dayjs().quarter()
    
    // Add quarters
    dayjs().add(1, 'quarter')
    
    // Start or end of quarter
    dayjs().startOf('quarter')
    dayjs().startOf('quarter', false) // end of quarter
  9. Initialize Day.js

    dev

    To create a Day.js object, call the dayjs() function. You can pass a native Date object, a timestamp, or a date string. You can also provide an optional configuration object to set the locale or other properties.

    If you pass an existing Day.js object to the dayjs() function, it returns a clone of that object to ensure immutability.

    import dayjs from 'dayjs'
    
    // From a Date object
    const d1 = dayjs(new Date())
    
    // From a string
    const d2 = dayjs('2023-01-01')
    
    // From a timestamp
    const d3 = dayjs(1672531200000)
    
    // Cloning an existing instance
    const d4 = dayjs(d1)
  10. Use strict parsing mode in customParseFormat

    dev

    When using customParseFormat, you can enable strict parsing to ensure the input string matches the format exactly. If strict mode is enabled and the input does not match the format perfectly, the resulting Day.js object will be invalid.

    To enable strict mode, pass true as the third argument to dayjs().

    import dayjs from 'dayjs'
    import customParseFormat from 'dayjs/plugin/customParseFormat'
    
    dayjs.extend(customParseFormat)
    
    // Strict parsing: input must match format exactly
    const strictDate = dayjs('2023-05-25', 'YYYY-MM-DD', true)
    
    // This will be invalid because of the extra characters
    const invalidStrictDate = dayjs('2023-05-25 extra', 'YYYY-MM-DD', true)
    console.log(invalidStrictDate.isValid()) // false
  11. Use the Duration plugin to handle time spans

    dev

    The duration plugin extends dayjs to provide a Duration class, allowing you to represent and manipulate time spans (e.g., "2 hours", "3 days") independently of specific dates.

    Once the plugin is extended, you can create durations using several input types:

    • Milliseconds (Number): dayjs.duration(1000)
    • Units (Number + Unit): dayjs.duration(2, 'hours')
    • Object: dayjs.duration({ hours: 2, minutes: 30 })
    • ISO 8601 String: dayjs.duration('PT2H30M')

    Durations can be added to or subtracted from dayjs objects using the .add() and .subtract() methods.

    import dayjs from 'dayjs'
    import duration from 'dayjs/plugin/duration'
    
    dayjs.extend(duration)
    
    // Create a duration
    const dur = dayjs.duration(2, 'hours')
    
    // Add duration to a date
    const later = dayjs().add(dur)
    
    // Subtract duration from a date
    const earlier = dayjs().subtract(dur)