Relative Time and Durations in Dayjs

Produce phrases such as “3 hours ago”, build countdowns and present elapsed time in a way people understand at a glance.

Updated 15 November 20266 min readDisplay
Analogue clock face representing relative time and durations in Dayjs

Some timestamps are most useful when they describe distance rather than position. “Posted 3 hours ago” tells a reader more at a glance than “15 November 2026, 11:44”, and “Offer ends in 2 days” creates a clearer sense of timing than a bare deadline. Dayjs supports this style of output through the RelativeTime and Calendar plugins, while the Duration plugin models spans of time for timers, countdowns and reports. This guide explains all three, shows how to customise their wording and offers practical patterns for interfaces that update as time passes.

Why relative time matters

Human beings judge recency intuitively. In a social feed, a support inbox or a notification panel, the question people ask is “how long ago?” rather than “at what exact moment?”. Relative phrasing answers that question directly and removes the mental arithmetic of comparing a timestamp with the current time. It also adapts naturally across time zones, since “5 minutes ago” means the same thing everywhere.

There are limits, however. Relative time becomes vague for older items, and it is unsuitable where precision matters, such as legal records or financial transactions. A sensible pattern is to show relative time for recent events and switch to an absolute date beyond a threshold, with the exact timestamp always available in a tooltip.

Setting up the RelativeTime plugin

RelativeTime is a small plugin that adds four methods to every instance. Load it once, following the setup approach in our installation guide.

import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
dayjs.extend(relativeTime)

fromNow() and toNow()

The most common method is fromNow(), which describes how far an instance lies from the present.

dayjs().subtract(5, 'minute').fromNow()   // '5 minutes ago'
dayjs().add(2, 'day').fromNow()           // 'in 2 days'
dayjs().subtract(1, 'year').fromNow()     // 'a year ago'
dayjs().subtract(5, 'minute').fromNow(true)  // '5 minutes'

Passing true removes the suffix, leaving only the distance. toNow() works the same way but from the opposite perspective, describing the present relative to the instance.

from() and to()

To compare two arbitrary dates rather than one date and the present, use from() and to().

const launch = dayjs('2026-12-01')
const today = dayjs('2026-11-15')

launch.from(today)   // 'in 16 days'
today.to(launch)     // 'in 16 days'

How Dayjs chooses its wording

RelativeTime rounds distances into friendly buckets rather than reporting exact values. Anything under 45 seconds becomes “a few seconds”, 45 to 89 seconds becomes “a minute”, and so on through hours, days, months and years. This rounding is deliberate: “3 hours ago” is more readable than “3 hours, 12 minutes and 40 seconds ago”.

If your product needs different thresholds, perhaps showing minutes up to two hours, you can pass a configuration object when extending the plugin. The thresholds option defines the boundaries and the rounding option controls whether values are rounded or floored.

dayjs.extend(relativeTime, {
  thresholds: [
    { l: 's', r: 1 },
    { l: 'm', r: 1 },
    { l: 'mm', r: 119, d: 'minute' },
    { l: 'h', r: 1 },
    { l: 'hh', r: 23, d: 'hour' },
    { l: 'd', r: 1 },
    { l: 'dd', r: 29, d: 'day' },
    { l: 'M', r: 1 },
    { l: 'MM', r: 11, d: 'month' },
    { l: 'y', r: 1 },
    { l: 'yy', d: 'year' }
  ],
  rounding: Math.floor
})

Customising relative phrases

The text itself comes from the active locale. To change the wording in English, for example to write “just now” instead of “a few seconds ago”, use the UpdateLocale plugin.

import updateLocale from 'dayjs/plugin/updateLocale'
dayjs.extend(updateLocale)

dayjs.updateLocale('en', {
  relativeTime: {
    future: 'in %s', past: '%s ago',
    s: 'moments', m: 'a minute', mm: '%d minutes',
    h: 'an hour', hh: '%d hours', d: 'a day', dd: '%d days',
    M: 'a month', MM: '%d months', y: 'a year', yy: '%d years'
  }
})

Because the phrases live in the locale, switching language automatically translates relative output too. Load the French locale and fromNow() returns “il y a 5 minutes”. Our locales and internationalisation guide covers loading and switching languages in detail.

Calendar time with the Calendar plugin

Between strictly relative and strictly absolute lies calendar time: “Today at 14:44”, “Yesterday at 09:10” or “Last Monday at 18:00”. This style suits chat applications and activity logs well, because it combines a familiar reference point with a precise time.

import calendar from 'dayjs/plugin/calendar'
dayjs.extend(calendar)

dayjs().subtract(1, 'day').calendar()
// 'Yesterday at 2:44 PM'

dayjs().calendar(null, {
  sameDay: '[Today at] HH:mm',
  lastDay: '[Yesterday at] HH:mm',
  lastWeek: '[Last] dddd [at] HH:mm',
  sameElse: 'D MMM YYYY'
})

The second argument accepts format strings for each bucket, using the same tokens described in our formatting guide. Literal words must be escaped in square brackets.

Modelling spans with the Duration plugin

A duration is a length of time not tied to any particular date: 90 minutes, 3 days, 1 year and 2 months. The Duration plugin introduces dayjs.duration() for creating, reading and formatting such values.

import duration from 'dayjs/plugin/duration'
dayjs.extend(duration)

const d = dayjs.duration(90, 'minutes')
d.hours()          // 1
d.minutes()        // 30
d.asMinutes()      // 90
d.humanize()       // 'an hour' (requires RelativeTime)
d.format('HH:mm')  // '01:30'

There is an important difference between the getter methods and the as methods. hours() returns the hours component of the duration, while asHours() returns the total length expressed in hours. For 90 minutes, hours() is 1 and asHours() is 1.5.

Creating durations from differences

Durations pair naturally with diff(), covered in our manipulation and comparison guide.

const start = dayjs('2026-11-15T09:00')
const end = dayjs('2026-11-15T17:45')
const worked = dayjs.duration(end.diff(start))

worked.format('H[h] m[m]')   // '8h 45m'

Durations also accept ISO 8601 duration strings such as P1DT2H, and objects such as { hours: 2, minutes: 15 }, which makes them convenient for configuration files and APIs.

Building a countdown timer

A countdown combines a target date, a duration and a regular update. The following sketch updates once per second and stops when the target is reached.

const target = dayjs('2026-12-31T23:59:59')

function tick() {
  const ms = target.diff(dayjs())
  if (ms <= 0) return render('Happy New Year')
  const left = dayjs.duration(ms)
  render(`${Math.floor(left.asDays())}d ${left.format('HH:mm:ss')}`)
  setTimeout(tick, 1000)
}
tick()

Using Math.floor(left.asDays()) for the day count avoids a subtle problem: the duration format's day token only shows the days component within a month, so long countdowns need the total calculated separately.

Keeping relative labels fresh

A label that says “a few seconds ago” becomes wrong after a few minutes if nothing updates it. In interfaces where items stay on screen, refresh relative labels on a timer. Updating every minute is enough for most feeds, and the cost is negligible because formatting is fast. In component frameworks, a single shared clock that triggers a re-render is tidier than separate timers for every item.

Accessibility deserves attention as well. Wrap relative labels in a <time> element with a machine-readable datetime attribute and provide the absolute date in a title. Screen readers and search engines then have the exact value, while sighted users enjoy the friendlier text.

Choosing between relative and absolute dates

Relative phrasing is not always the right choice, and deciding when to use it is as important as knowing how. A practical rule many products follow is to show relative time for anything within the last week, then switch to an absolute date for older items. This keeps recent activity vivid while ensuring that older records remain precise and easy to locate.

function smartDate(value) {
  const d = dayjs(value)
  return dayjs().diff(d, 'day') < 7 ? d.fromNow() : d.format('D MMM YYYY')
}

Context matters too. In a chat application, “Yesterday at 21:15” from the Calendar plugin often reads better than “a day ago”. In a document editor, “Edited 5 minutes ago” reassures people that their work has been saved. In financial or legal records, absolute timestamps with time zone labels are essential, and relative phrasing should appear only as a secondary hint, if at all.

Durations in reports and billing

Durations are invaluable beyond countdowns. Time-tracking tools sum durations to produce weekly totals, support desks measure response times against service targets and billing systems calculate usage periods. In each case, adding durations together with duration.add() or summing millisecond values before creating a single duration keeps calculations accurate.

When presenting totals, choose units that match the reader's expectations. Support managers think in hours and minutes, finance teams in days or months, and engineers sometimes in milliseconds. The as methods convert a duration into any of these units, while format() produces tidy strings for tables and exports.

Be aware that months and years vary in length, so durations expressed in those units are approximations. For precise calendar calculations, such as adding exactly one month to a subscription date, use the manipulation methods described in our manipulation and comparison guide instead of durations.

Localising relative output

Relative phrases carry grammatical complexity in many languages, with plural forms, gender and word order that differ greatly from English. The locale files bundled with Dayjs handle these rules for you, which is one of the strongest reasons to rely on RelativeTime instead of building phrases manually. Simply load the locale and the correct wording appears automatically, as our locales guide explains.

Conclusion

Relative time, calendar phrasing and durations let Dayjs describe time the way people naturally think about it. RelativeTime turns differences into readable phrases with configurable thresholds, Calendar anchors moments to familiar reference points and Duration models spans for timers, reports and countdowns. Customise the wording through locales, refresh labels that stay on screen and always keep the precise timestamp available for those who need it. Used thoughtfully, these tools make interfaces feel more responsive and more human.