Метод isSame используется для проверки равенства двух
дат или времени. Он позволяет определить, совпадают ли значения
полностью или в пределах определённой единицы времени: года, месяца,
дня, часа и так далее.
Сигнатура метода:
dayjs().isSame(date)
dayjs().isSame(date, unit)
Если второй аргумент не указан, сравнение выполняется с точностью до миллисекунды.
const day1 = dayjs('2025-03-10')
const day2 = dayjs('2025-03-10')
console.log(day1.isSame(day2)) // true
Пример с разными значениями:
const day1 = dayjs('2025-03-10')
const day2 = dayjs('2025-03-11')
console.log(day1.isSame(day2)) // false
Метод принимает не только объект Day.js, но и стандартный
Date.
const current = dayjs()
const nativeDate = new Date()
console.log(current.isSame(nativeDate))
В качестве аргумента можно передавать строку с датой.
const result = dayjs('2025-05-01').isSame('2025-05-01')
console.log(result) // true
Второй аргумент определяет уровень точности сравнения.
Поддерживаются следующие единицы:
yearmonthweekdayhourminutesecondconst d1 = dayjs('2025-01-10')
const d2 = dayjs('2025-11-25')
console.log(d1.isSame(d2, 'year')) // true
Несмотря на разные месяцы и дни, год совпадает.
const d1 = dayjs('2025-03-01')
const d2 = dayjs('2025-03-29')
console.log(d1.isSame(d2, 'month')) // true
Если месяц отличается:
const d1 = dayjs('2025-03-31')
const d2 = dayjs('2025-04-01')
console.log(d1.isSame(d2, 'month')) // false
const d1 = dayjs('2025-06-15 08:00')
const d2 = dayjs('2025-06-15 22:30')
console.log(d1.isSame(d2, 'day')) // true
Время игнорируется, поскольку сравнение выполняется только по дню.
const d1 = dayjs('2025-06-15 10:15:00')
const d2 = dayjs('2025-06-15 10:59:59')
console.log(d1.isSame(d2, 'hour')) // true
const d1 = dayjs('2025-06-15 10:45:10')
const d2 = dayjs('2025-06-15 10:45:59')
console.log(d1.isSame(d2, 'minute')) // true
const d1 = dayjs('2025-06-15 10:45:30.100')
const d2 = dayjs('2025-06-15 10:45:30.900')
console.log(d1.isSame(d2, 'second')) // true
Day.js поддерживает сокращённые варианты:
| Полная форма | Краткая форма |
|---|---|
| year | y |
| month | M |
| week | w |
| day | d |
| hour | h |
| minute | m |
| second | s |
Пример:
const d1 = dayjs('2025-01-01')
const d2 = dayjs('2025-12-31')
console.log(d1.isSame(d2, 'y')) // true
При использовании единицы времени Day.js сравнивает не только её, но и все более крупные единицы.
Например:
const d1 = dayjs('2025-03-10')
const d2 = dayjs('2026-03-10')
console.log(d1.isSame(d2, 'month')) // false
Несмотря на одинаковый месяц, годы различаются.
Логика сравнения для 'month':
Для 'day':
const isToday = dayjs().isSame(dayjs(), 'day')
console.log(isToday) // true
const birthday = dayjs('1995-08-20')
const today = dayjs()
const isBirthday = today.isSame(birthday, 'day') &&
today.isSame(birthday, 'month')
console.log(isBirthday)
Более корректный вариант:
const isBirthday =
today.date() === birthday.date() &&
today.month() === birthday.month()
const dates = [
dayjs('2025-01-01'),
dayjs('2025-01-01'),
dayjs('2025-01-02')
]
const result = dates.filter(date =>
date.isSame('2025-01-01', 'day')
)
console.log(result.length) // 2
utcПри работе с часовыми поясами результаты могут отличаться.
dayjs.extend(utc)
const d1 = dayjs.utc('2025-01-01T00:00:00Z')
const d2 = dayjs('2025-01-01T03:00:00+03:00')
console.log(d1.isSame(d2)) // true
Обе даты представляют один и тот же момент времени.
timezonedayjs.extend(utc)
dayjs.extend(timezone)
const moscow = dayjs.tz('2025-06-01 12:00', 'Europe/Moscow')
const almaty = dayjs.tz('2025-06-01 14:00', 'Asia/Almaty')
console.log(moscow.isSame(almaty)) // true
const invalid = dayjs('invalid-date')
console.log(invalid.isValid()) // false
console.log(invalid.isSame(dayjs())) // false
Если хотя бы одна дата невалидна, метод возвращает
false.
const isCurrentHour = dayjs('2025-06-10 15:20')
.isSame(dayjs(), 'hour')
console.log(isCurrentHour)
Для работы с кварталами требуется плагин
QuarterOfYear.
dayjs.extend(quarterOfYear)
const d1 = dayjs('2025-02-15')
const d2 = dayjs('2025-03-20')
console.log(d1.isSame(d2, 'quarter')) // true
Для недель используется единица week.
const d1 = dayjs('2025-05-12')
const d2 = dayjs('2025-05-16')
console.log(d1.isSame(d2, 'week'))
Результат зависит от локали и первого дня недели.
isSame от обычного сравненияСравнение через операторы:
day1 === day2
не работает корректно для объектов Day.js.
Пример:
const d1 = dayjs('2025-01-01')
const d2 = dayjs('2025-01-01')
console.log(d1 === d2) // false
Каждый вызов dayjs() создаёт новый объект.
Правильный вариант:
console.log(d1.isSame(d2)) // true
valueOfМетод valueOf() возвращает timestamp в
миллисекундах.
const d1 = dayjs('2025-01-01')
const d2 = dayjs('2025-01-01')
console.log(d1.valueOf() === d2.valueOf()) // true
Однако isSame удобнее и читаемее.
const lastActivity = dayjs('2025-06-01 14:25')
const currentTime = dayjs()
const activeNow = lastActivity.isSame(currentTime, 'minute')
console.log(activeNow)
const messages = [
{ text: 'A', date: dayjs('2025-06-01 10:00') },
{ text: 'B', date: dayjs('2025-06-01 15:00') },
{ text: 'C', date: dayjs('2025-06-02 09:00') }
]
const sameDayMessages = messages.filter(message =>
message.date.isSame('2025-06-01', 'day')
)
console.log(sameDayMessages)
const deadline = dayjs('2025-07-01')
const today = dayjs()
if (today.isSame(deadline, 'day')) {
console.log('Последний день')
}
isBeforeconst start = dayjs('2025-01-01')
const current = dayjs('2025-01-10')
const result =
current.isSame(start, 'month') ||
current.isBefore(start)
console.log(result)
isAfterconst paymentDate = dayjs('2025-06-10')
const now = dayjs()
if (now.isAfter(paymentDate) && !now.isSame(paymentDate, 'day')) {
console.log('Платёж просрочен')
}
isSame работает быстро, поскольку сравнение основано на
числовых timestamp-значениях. Метод подходит для:
===dayjs() === dayjs()
Результат всегда будет false.
d1.isSame(d2, 'days')
Следует использовать:
d1.isSame(d2, 'day')
const d1 = dayjs.utc('2025-01-01T00:00:00Z')
const d2 = dayjs('2025-01-01T00:00:00')
Эти значения могут представлять разные моменты времени.
| Единица | Краткая форма |
|---|---|
| year | y |
| quarter | Q |
| month | M |
| week | w |
| day | d |
| hour | h |
| minute | m |
| second | s |
| millisecond | ms |
isSameDate и объекты Day.js;