Skip to content
Youngho Chaa cha cha
TwitterHomepage

Day.js

javascript, npm2 min read

Day.js is a minimalist JavaScript library for parsing, validating, manipulating, and formatting dates. It's often lauded for its simplicity and small footprint. The library is designed to work both in the browser and in Node.js.

Here are some key features of Day.js:

  • Immutable and Chainable: Day.js creates date wrapper objects that are immutable. This means that every manipulation or formatting operation returns a new Day.js object, allowing methods to be chained.
  • Simple API: Day.js tries to keep the API surface simple and consistent, which makes it easier for developers to work with dates without a steep learning curve.
  • Plugin System: While the core library is small, Day.js supports a plugin system, allowing you to extend its functionality with plugins such as advanced parsing, custom parsing, timezone support, and more.
  • Internationalization: Day.js comes with built-in support for internationalization and can be easily localized to support various languages and formats.
  • Compatibility with Moment.js: Day.js offers an API that is largely compatible with that of Moment.js, one of the most popular date libraries. This makes it easier to migrate from Moment.js to Day.js for those looking for a smaller footprint.

Here's an example of how you might use Day.js:

const dayjs = require('dayjs');
// Parse a date
let date = dayjs('2023-11-02');
// Format a date
console.log(date.format('YYYY-MM-DD')); // Output: 2023-11-02
// Add time
date = date.add(1, 'day');
// Check if a date is before/after another date
let now = dayjs();
console.log(date.isAfter(now)); // Output: depends on the current date and time
// Use a plugin
const advancedFormat = require('dayjs/plugin/advancedFormat');
dayjs.extend(advancedFormat);
console.log(date.format('Q')); // Output: Quarter of the year
// ISO String
dayjs('2019-01-25').toISOString() // '2019-01-25T02:00:00.000Z'

Custom parsing

import dayjs from 'dayjs'
import customParseFormat from 'dayjs/plugin/customParseFormat'
dayjs.extend(customParseFormat)
const localizedDate = dayjs('2023年11月02日', 'YYYY年MM月DD日');
console.log(localizedDate.format()); // Outputs the localized format
function getWarrantyDate(
installationDate: string,
warrantyYear: number
): string {
if (warrantyYear === -1) return ''
const date = dayjs(installationDate, 'DD/MM/YYYY').add(warrantyYear, 'year')
return date.format('DD/MM/YYYY')
}

Format

dayjs().format('DD/MM/YYYY') // 26/11/2023
dayjs().toISOString() // 2023-11-26T10:00:00
© 2024 by Youngho Chaa cha cha. All rights reserved.
Theme by LekoArts