В библиотеке Day.js количество дней в текущем месяце определяется
методом daysInMonth(). Метод возвращает целое число,
соответствующее количеству календарных дней в месяце выбранной даты.
const dayjs = require('dayjs')
const date = dayjs('2025-02-10')
console.log(date.daysInMonth()) // 28
Метод автоматически учитывает:
dayjs().daysInMonth()
Возвращаемое значение:
number
Наиболее распространённый сценарий — определение количества дней в месяце текущей даты.
const dayjs = require('dayjs')
const days = dayjs().daysInMonth()
console.log(days)
Если код выполняется в январе:
31
Если в феврале невисокосного года:
28
Метод особенно полезен при работе с заранее известными датами.
const dayjs = require('dayjs')
console.log(dayjs('2025-04-15').daysInMonth()) // 30
console.log(dayjs('2025-01-15').daysInMonth()) // 31
console.log(dayjs('2025-02-15').daysInMonth()) // 28
daysInMonth() автоматически определяет високосный
год.
const dayjs = require('dayjs')
console.log(dayjs('2024-02-01').daysInMonth()) // 29
console.log(dayjs('2025-02-01').daysInMonth()) // 28
Проверка выполняется по стандартным правилам календаря Gregorian.
Метод часто применяется в логике календарей, расписаний и отчётов.
const dayjs = require('dayjs')
const date = dayjs('2024-02-10')
if (date.daysInMonth() === 29) {
console.log('Високосный февраль')
}
Количество дней месяца удобно использовать для получения последней даты месяца.
const dayjs = require('dayjs')
const date = dayjs('2025-06-12')
const lastDay = date.date(date.daysInMonth())
console.log(lastDay.format('YYYY-MM-DD'))
Результат:
2025-06-30
Метод полезен при построении календарных интерфейсов.
const dayjs = require('dayjs')
const date = dayjs('2025-03-01')
const totalDays = date.daysInMonth()
for (let day = 1; day <= totalDays; day++) {
console.log(day)
}
Результат:
1
2
3
...
31
При работе с пользовательским вводом количество дней месяца помогает валидировать дату.
const dayjs = require('dayjs')
function isValidDay(year, month, day) {
const date = dayjs(`${year}-${month}-01`)
return day <= date.daysInMonth()
}
console.log(isValidDay(2025, 2, 29)) // false
console.log(isValidDay(2024, 2, 29)) // true
endOf()Метод daysInMonth() может использоваться совместно с
endOf() для сравнения результатов.
const dayjs = require('dayjs')
const date = dayjs('2025-08-10')
console.log(date.daysInMonth())
console.log(date.endOf('month').date())
Результат:
31
31
const dayjs = require('dayjs')
for (let month = 1; month <= 12; month++) {
const date = dayjs(`2025-${String(month).padStart(2, '0')}-01`)
console.log(
date.format('MMMM'),
date.daysInMonth()
)
}
Пример результата:
January 31
February 28
March 31
April 30
...
Количество дней не зависит от локали, однако локализация влияет на форматирование.
const dayjs = require('dayjs')
const localeData = require('dayjs/plugin/localeData')
require('dayjs/locale/ru')
dayjs.extend(localeData)
dayjs.locale('ru')
const date = dayjs('2025-02-01')
console.log(date.format('MMMM'))
console.log(date.daysInMonth())
Результат:
февраль
28
const dayjs = require('dayjs')
const now = dayjs()
const totalDays = now.daysInMonth()
const currentDay = now.date()
const remainingDays = totalDays - currentDay
console.log(remainingDays)
const dayjs = require('dayjs')
function isLongMonth(date) {
return date.daysInMonth() === 31
}
console.log(isLongMonth(dayjs('2025-07-01'))) // true
console.log(isLongMonth(dayjs('2025-09-01'))) // false
const dayjs = require('dayjs')
function getMonthDays(date) {
const days = []
for (let i = 1; i <= date.daysInMonth(); i++) {
days.push(i)
}
return days
}
console.log(getMonthDays(dayjs('2025-05-01')))
Результат:
[
1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
11, 12, 13, 14, 15,
16, 17, 18, 19, 20,
21, 22, 23, 24, 25,
26, 27, 28, 29, 30,
31
]
Нативный JavaScript требует более сложной конструкции.
const date = new Date(2025, 1, 0)
console.log(date.getDate())
const dayjs = require('dayjs')
console.log(dayjs('2025-01-01').daysInMonth())
Подход в Day.js делает код:
const dayjs = require('dayjs')
const date = dayjs('2025-03-10')
const days = date.daysInMonth()
console.log(date.format('YYYY-MM-DD'))
console.log(days)
Результат:
2025-03-10
31
daysInMonth() не требует дополнительных плагинов и
входит в базовую функциональность библиотеки.
Метод может использоваться после других операций.
const dayjs = require('dayjs')
const days = dayjs()
.add(1, 'year')
.month(1)
.daysInMonth()
console.log(days)
month()const dayjs = require('dayjs')
const date = dayjs().month(6)
console.log(date.daysInMonth())
year()const dayjs = require('dayjs')
const date = dayjs().year(2032)
console.log(date.daysInMonth())
subtract()const dayjs = require('dayjs')
const previousMonth = dayjs().subtract(1, 'month')
console.log(previousMonth.daysInMonth())
Метод daysInMonth() активно используется в:
В Day.js месяцы внутри метода month() нумеруются с
нуля.
dayjs().month(0) // январь
dayjs().month(1) // февраль
Пример:
const date = dayjs().month(1)
console.log(date.daysInMonth())
Результат:
28
date() и daysInMonth()const date = dayjs('2025-06-18')
console.log(date.date()) // 18
console.log(date.daysInMonth()) // 30
date() — номер дня месяца;daysInMonth() — количество дней в месяце.| Метод | Назначение |
|---|---|
daysInMonth() |
Количество дней в месяце |
date() |
День месяца |
day() |
День недели |
month() |
Месяц |
year() |
Год |
endOf('month') |
Конец месяца |