dayjs is a minimalist JavaScript library for parsing, validating, manipulating, and displaying dates and times in browsers and Node.js. It's designed to be lightweight (only 2KB gzipped) and comes with a simple, familiar API that is largely compatible with Moment.js, making it an excellent modern alternative.
Why Use dayjs?
1. Lightweight: At just 2KB (gzipped), it's significantly smaller than other date libraries, leading to faster page loads and less bandwidth usage.
2. Immutable: All API operations return a new `Dayjs` object, ensuring that original date objects are not mutated. This promotes predictable state management and easier debugging.
3. Moment.js Compatible API: Developers familiar with Moment.js can quickly adapt to dayjs due to its similar API design, reducing the learning curve.
4. Extensible: dayjs supports plugins to add extra functionality like timezone support, advanced formatting, relative time, etc., without bloating the core library.
5. Internationalization (i18n): It offers comprehensive internationalization support through locale data plugins.
6. Modern Browser & Node.js Support: Works seamlessly across various environments.
Core Features and Operations:
- Creation: Create `Dayjs` objects from current date, strings, JavaScript `Date` objects, or Unix timestamps.
- `dayjs()`: Current date and time.
- `dayjs('2023-10-27')`: From a string.
- `dayjs(new Date())`: From a native Date object.
- Formatting: Display dates and times in various custom formats.
- `dayjs().format('YYYY-MM-DD HH:mm:ss')`
- Manipulation: Add or subtract time units, get start/end of time units.
- `dayjs().add(1, 'day')`
- `dayjs().subtract(2, 'hour')`
- `dayjs().startOf('month')`
- `dayjs().endOf('year')`
- Querying: Compare dates, get differences, check if a date is before/after/same as another.
- `dayjs().isBefore(anotherDayjsObject)`
- `dayjs().isSame(anotherDayjsObject, 'day')`
- `dayjs().diff(anotherDayjsObject, 'hour')`
- Plugins: Extend functionality with optional plugins, e.g., `dayjs.extend(timezone)`, `dayjs.extend(advancedFormat)`.
Installation:
To install dayjs, you can use npm or yarn:
```bash
npm install dayjs
# OR
yarn add dayjs
```
Example Code
```jsx
import React, { useState, useEffect } from 'react';
import dayjs from 'dayjs';
// Optional: Import and extend plugins for additional functionality
// import advancedFormat from 'dayjs/plugin/advancedFormat';
// dayjs.extend(advancedFormat);
function DayjsExample() {
const [currentDateTime, setCurrentDateTime] = useState('');
const [manipulatedDate, setManipulatedDate] = useState('');
const [monthBoundaries, setMonthBoundaries] = useState('');
const [dateDifference, setDateDifference] = useState(0);
const [isSameDay, setIsSameDay] = useState('');
useEffect(() => {
// 1. Get current date and time and format it
const now = dayjs();
setCurrentDateTime(now.format('YYYY-MM-DD HH:mm:ss [Current Time]'));
// 2. Manipulate a specific date
const specificDate = dayjs('2023-04-10T14:30:00');
const futureDate = specificDate.add(5, 'day').subtract(2, 'hour');
setManipulatedDate(futureDate.format('MMMM D, YYYY [at] HH:mm'));
// 3. Get start and end of the current month
const startOfMonth = now.startOf('month').format('dddd, MMMM D, YYYY');
const endOfMonth = now.endOf('month').format('dddd, MMMM D, YYYY');
setMonthBoundaries(`Start: ${startOfMonth} | End: ${endOfMonth}`);
// 4. Calculate difference between two dates
const dateA = dayjs('2023-01-01');
const dateB = dayjs('2023-03-15');
const diffDays = dateB.diff(dateA, 'day'); // Difference in days
setDateDifference(diffDays);
// 5. Querying: Check if two dates are the same (at day granularity)
const dateToCheck1 = dayjs('2023-10-27T10:00:00');
const dateToCheck2 = dayjs('2023-10-27T15:30:00');
setIsSameDay(dateToCheck1.isSame(dateToCheck2, 'day') ? 'Yes, they are the same day.' : 'No, they are different days.');
}, []); // Empty dependency array means this effect runs once after the initial render
return (
<div style={{ padding: '20px', fontFamily: 'Arial, sans-serif' }}>
<h2>dayjs in React Example</h2>
<p><strong>1. Current Date & Time:</strong> {currentDateTime}</p>
<p>
<strong>2. Manipulated Date (2023-04-10T14:30:00 + 5 days - 2 hours):</strong>
<br />{manipulatedDate}
</p>
<p>
<strong>3. Current Month Boundaries:</strong>
<br />{monthBoundaries}
</p>
<p><strong>4. Difference between 2023-01-01 and 2023-03-15:</strong> {dateDifference} days</p>
<p>
<strong>5. Are '2023-10-27T10:00:00' and '2023-10-27T15:30:00' the same day?</strong>
<br />{isSameDay}
</p>
<p><strong>Is '2023-10-01' before '2023-10-27'?</strong> {dayjs('2023-10-01').isBefore('2023-10-27') ? 'Yes' : 'No'}</p>
<p><strong>Is '2023-11-01' after '2023-10-27'?</strong> {dayjs('2023-11-01').isAfter('2023-10-27') ? 'Yes' : 'No'}</p>
</div>
);
}
export default DayjsExample;
```








dayjs