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)