Manipulating and Comparing Dates with Dayjs

Add and subtract time, jump to the start or end of a period, measure differences and compare dates without ever mutating the original value.

Updated 15 November 20266 min readManipulation
Person planning tasks in a notebook, representing date calculations in Dayjs

Displaying a date is only half the story. Most applications also need to calculate with dates: a subscription renews in thirty days, an invoice is overdue after the end of the month, a report covers the previous quarter and a booking must fall between two limits. Dayjs provides a compact, chainable set of methods for exactly this work. This guide covers adding and subtracting time, moving to the start or end of a period, reading and setting individual units, measuring differences and comparing dates, always with immutability in mind.

Immutability: the rule that shapes everything

Before looking at individual methods, it is worth understanding the principle that governs them all. In Dayjs, every manipulation returns a new instance. The original value is never changed.

const start = dayjs('2026-11-15')
const later = start.add(1, 'week')

start.format('D MMM')  // '15 Nov' (unchanged)
later.format('D MMM')  // '22 Nov'

This behaviour contrasts with Moment.js, where add() alters the object in place. Immutability removes a whole family of bugs in which a shared date is modified unexpectedly by another part of the program. It also fits naturally with modern frameworks that detect changes by comparing references. The only habit to build is assigning the result: calling start.add(1, 'day') on its own line achieves nothing.

Adding and subtracting time in Dayjs

The add() and subtract() methods take an amount and a unit. Units can be written in full, in plural form or as short aliases.

dayjs().add(30, 'day')
dayjs().subtract(2, 'hours')
dayjs().add(1, 'M')        // one month
dayjs().subtract(1, 'y')   // one year
dayjs().add(90, 'minute')

Supported units include millisecond, second, minute, hour, day, week, month and year. With the QuarterOfYear plugin you can also add quarters. Month arithmetic handles varying month lengths sensibly: adding one month to 31 January gives the last day of February rather than spilling into March, which is almost always the behaviour users expect.

Because each call returns a new instance, operations chain fluently:

const deadline = dayjs().add(1, 'month').subtract(1, 'day').hour(17).minute(0)

Start and end of a period

Reports, filters and calendars constantly need the boundaries of a period. The startOf() and endOf() methods move a date to the first or last moment of a unit.

dayjs('2026-11-15T14:44').startOf('day')    // 15 Nov 00:00:00.000
dayjs('2026-11-15T14:44').endOf('month')    // 30 Nov 23:59:59.999
dayjs('2026-11-15').startOf('year')         // 1 Jan 2026
dayjs('2026-11-15').startOf('week')         // depends on locale

The start of a week depends on the active locale. In the default English locale weeks begin on Sunday, whereas in British English and many European locales they begin on Monday. If week boundaries matter to your product, load the appropriate locale or use the IsoWeek plugin, which offers startOf('isoWeek') and always starts on Monday. Our locales guide explains how week settings are configured.

Building date ranges

Combining these methods produces clean ranges for queries and filters:

const lastMonth = dayjs().subtract(1, 'month')
const range = {
  from: lastMonth.startOf('month').toISOString(),
  to:   lastMonth.endOf('month').toISOString()
}

Getting and setting units

Each unit has a getter and setter that share the same name. Called without an argument the method reads the value; called with one it returns a new instance with that unit changed.

const d = dayjs('2026-11-15T14:44')

d.year()        // 2026
d.month()       // 10 (zero-indexed, November)
d.date()        // 15 (day of month)
d.day()         // 0 (Sunday)
d.hour(9)       // new instance at 09:44
d.set('minute', 0)
d.get('hour')   // 14

Two details deserve emphasis. Months are zero-indexed, so January is 0 and December is 11, matching the native Date object. And date() refers to the day of the month, while day() refers to the day of the week. Mixing them up is a frequent source of off-by-a-few-days errors.

Measuring differences with diff()

The diff() method returns the difference between two dates in a chosen unit. By default it returns milliseconds and truncates the result toward zero.

const a = dayjs('2026-12-25')
const b = dayjs('2026-11-15')

a.diff(b)                 // milliseconds
a.diff(b, 'day')          // 40
a.diff(b, 'week')         // 5
a.diff(b, 'month', true)  // 1.32... (floating point)

Passing true as the third argument returns a precise floating-point value instead of a truncated integer, which is useful for progress bars and pro-rata billing. The order of arguments matters: a.diff(b) is positive when a is later than b. When you want to show the result as friendly text, such as “in 40 days”, pair it with the techniques in our relative time and durations guide.

Calculating age

A classic use of diff() is calculating someone's age, which must account for whether their birthday has occurred yet this year. Fortunately, the month-based calculation in Dayjs handles that automatically.

const age = dayjs().diff(dayjs('1995-06-20'), 'year')

Comparing dates in Dayjs

Three core methods answer the question of order: isBefore(), isAfter() and isSame(). Each accepts an optional unit that sets the granularity of the comparison.

const due = dayjs('2026-11-30')

dayjs().isBefore(due)              // true if now is earlier
dayjs().isAfter(due, 'day')        // compares by calendar day only
dayjs('2026-11-15T09:00').isSame('2026-11-15T18:00', 'day')  // true

Granularity is powerful. Comparing by 'day' ignores the time of day, so two moments on the same date count as the same. Comparing by 'month' asks whether both fall in the same calendar month. Choosing the right unit often removes the need for manual startOf() calls.

Comparison plugins

Several small plugins round out the comparison toolkit:

  • IsSameOrBefore and IsSameOrAfter express inclusive comparisons clearly.
  • IsBetween checks whether a date falls within a range, with a fourth argument such as '[]' to control whether the boundaries are included.
  • IsToday, IsTomorrow and IsYesterday answer common questions in a single readable call.
  • MinMax adds dayjs.min() and dayjs.max() for finding the earliest or latest of several dates.
import isBetween from 'dayjs/plugin/isBetween'
dayjs.extend(isBetween)

dayjs('2026-11-15').isBetween('2026-11-01', '2026-11-30', 'day', '[]')  // true

You can read more about loading and combining these in our plugins guide.

Practical Dayjs recipes

The following patterns appear in many production applications and illustrate how the methods work together.

  • Overdue check: dayjs().isAfter(invoice.dueDate, 'day') flags an invoice the day after it falls due.
  • Trial expiry: dayjs(user.createdAt).add(14, 'day') gives the end of a two-week trial.
  • Days remaining: dayjs(expiry).diff(dayjs(), 'day') powers a countdown badge.
  • Next weekday: add one day in a loop until day() is between 1 and 5, skipping weekends.
  • Month calendar grid: start from startOf('month').startOf('week') and add days until you pass endOf('month').endOf('week').

Pitfalls to watch for

Date arithmetic around daylight saving changes can surprise you. Adding 24 hours is not always the same as adding one day, because a day may contain 23 or 25 hours. Use calendar units such as 'day' when you mean the same clock time tomorrow, and fixed units such as 'hour' when you mean an exact duration. When your application spans regions, perform calculations in UTC or in an explicit zone, as described in the time zones and UTC guide.

Finally, always ensure the inputs are valid before calculating. An invalid date propagates silently through add() and diff(), producing NaN results that are hard to trace. The parsing guide describes how to validate values at the boundary.

Sorting and grouping dates

Lists of events, orders or messages often need sorting by date. Because a Dayjs instance converts to a number with valueOf(), sorting is straightforward: subtract one value from another inside the comparison function. For arrays of ISO strings, parsing once before sorting is faster and clearer than parsing repeatedly inside the comparator.

orders.sort((a, b) => dayjs(a.createdAt).valueOf() - dayjs(b.createdAt).valueOf())

Grouping works in a similar way. To build a monthly report, compute a key such as dayjs(order.createdAt).format('YYYY-MM') for each record and collect records that share the same key. Weekly groupings can use startOf('week') or, for ISO weeks, the IsoWeek plugin, so that every record falls into exactly one bucket.

Working with business rules

Many applications encode rules such as “orders placed after 14:00 ship the next working day” or “refunds are available for 30 days after delivery”. Express these rules in small, well-named functions that take a date and return a date or a boolean. Keeping them pure, with no hidden reference to the current time, makes them easy to test with fixed inputs.

Pass the current moment in as an argument rather than calling dayjs() inside the function. A rule written as isRefundable(deliveredAt, now) can be tested for any scenario, including the last second of the refund window, without manipulating the system clock. This small discipline pays dividends as rules multiply and change over time.

Where rules depend on holidays or regional calendars, consider writing a custom plugin, as described in our plugins guide, so that every part of the codebase applies the same logic.

Conclusion

Manipulation and comparison in Dayjs are built on a few clear, chainable methods: add() and subtract() move through time, startOf() and endOf() find boundaries, getters and setters adjust individual units, diff() measures distance and the query methods establish order. Immutability guarantees that none of these operations surprise you by changing a value elsewhere. Choose calendar units for calendar logic, fixed units for exact durations, and lean on the small comparison plugins for readable, intention-revealing code.