Функция roundToNearestMinutes из библиотеки date-fns
используется для округления даты до ближайшего количества минут. Метод
особенно полезен при работе с:
Функция не изменяет исходный объект Date, а возвращает
новый экземпляр даты.
roundToNearestMinutes(date, options)
| Аргумент | Тип | Описание |
|---|---|---|
date |
Date \| Number |
Исходная дата |
options |
Object |
Дополнительные параметры |
import { roundToNearestMinutes } fr om 'date-fns'
const date = new Date(2025, 3, 10, 12, 17)
const result = roundToNearestMinutes(date)
console.log(result)
Результат:
2025-04-10T12:17:00.000Z
По умолчанию функция округляет до ближайшей минуты без дополнительного интервала.
Наиболее распространённый сценарий — округление времени до фиксированных интервалов.
import { roundToNearestMinutes } fr om 'date-fns'
const date = new Date(2025, 3, 10, 12, 17)
const result = roundToNearestMinutes(date, {
nearestTo: 5
})
console.log(result)
Результат:
12:15
Функция анализирует количество минут и выбирает ближайшее значение относительно указанного интервала.
5| Исходное время | Результат |
|---|---|
| 12:01 | 12:00 |
| 12:02 | 12:00 |
| 12:03 | 12:05 |
| 12:07 | 12:05 |
| 12:08 | 12:10 |
nearestToroundToNearestMinutes(date, {
nearestTo: number
})
Значение должно быть:
0;30.nearestTo: 1
nearestTo: 5
nearestTo: 10
nearestTo: 15
nearestTo: 30
nearestTo: 0
nearestTo: -5
nearestTo: 45
Если передать недопустимое значение, будет выброшено исключение
RangeError.
import { roundToNearestMinutes } from 'date-fns'
const date = new Date()
roundToNearestMinutes(date, {
nearestTo: 45
})
Ошибка:
RangeError: nearestTo must be between 1 and 30
По умолчанию используется стандартное математическое округление.
import { roundToNearestMinutes } from 'date-fns'
const date1 = new Date(2025, 3, 10, 12, 12)
const date2 = new Date(2025, 3, 10, 12, 13)
console.log(
roundToNearestMinutes(date1, {
nearestTo: 5
})
)
console.log(
roundToNearestMinutes(date2, {
nearestTo: 5
})
)
Результат:
12:10
12:15
roundingMethodФункция поддерживает разные алгоритмы округления.
| Метод | Описание |
|---|---|
round |
Математическое округление |
floor |
Округление вниз |
ceil |
Округление вверх |
trunc |
Усечение дробной части |
roundСтандартное округление.
import { roundToNearestMinutes } from 'date-fns'
const result = roundToNearestMinutes(
new Date(2025, 3, 10, 12, 13),
{
nearestTo: 5,
roundingMethod: 'round'
}
)
console.log(result)
Результат:
12:15
floorВсегда округляет вниз.
import { roundToNearestMinutes } from 'date-fns'
const result = roundToNearestMinutes(
new Date(2025, 3, 10, 12, 19),
{
nearestTo: 10,
roundingMethod: 'floor'
}
)
console.log(result)
Результат:
12:10
ceilВсегда округляет вверх.
import { roundToNearestMinutes } from 'date-fns'
const result = roundToNearestMinutes(
new Date(2025, 3, 10, 12, 11),
{
nearestTo: 10,
roundingMethod: 'ceil'
}
)
console.log(result)
Результат:
12:20
truncУдаляет дробную часть без математического округления.
import { roundToNearestMinutes } from 'date-fns'
const result = roundToNearestMinutes(
new Date(2025, 3, 10, 12, 19),
{
nearestTo: 10,
roundingMethod: 'trunc'
}
)
console.log(result)
Результат:
12:10
Функция учитывает секунды и миллисекунды при вычислениях.
import { roundToNearestMinutes } from 'date-fns'
const date = new Date(2025, 3, 10, 12, 14, 40)
const result = roundToNearestMinutes(date, {
nearestTo: 5
})
console.log(result)
Результат:
12:15
Поскольку значение ближе к 12:15, округление происходит
вверх.
import { roundToNearestMinutes } from 'date-fns'
const now = new Date()
const slot = roundToNearestMinutes(now, {
nearestTo: 15,
roundingMethod: 'ceil'
})
console.log(slot)
Пример:
09:00
09:15
09:30
09:45
Подход часто используется в:
При агрегации событий удобно приводить время к единому интервалу.
import { roundToNearestMinutes } from 'date-fns'
const events = [
new Date(2025, 3, 10, 10, 2),
new Date(2025, 3, 10, 10, 4),
new Date(2025, 3, 10, 10, 7)
]
const normalized = events.map(event =>
roundToNearestMinutes(event, {
nearestTo: 5
})
)
console.log(normalized)
Результат:
[
10:00,
10:05,
10:05
]
formatОбычно результат сразу форматируют.
import {
roundToNearestMinutes,
format
} from 'date-fns'
const date = new Date()
const rounded = roundToNearestMinutes(date, {
nearestTo: 15
})
console.log(
format(rounded, 'HH:mm')
)
Функция принимает timestamp в миллисекундах.
import { roundToNearestMinutes } from 'date-fns'
const timestamp = Date.now()
const result = roundToNearestMinutes(timestamp, {
nearestTo: 30
})
console.log(result)
date-fns придерживается принципа immutable API.
import { roundToNearestMinutes } from 'date-fns'
const original = new Date(2025, 3, 10, 12, 17)
const rounded = roundToNearestMinutes(original, {
nearestTo: 5
})
console.log(original)
console.log(rounded)
Исходный объект останется неизменным.
function roundMinutes(date, nearestTo) {
const ms = 1000 * 60 * nearestTo
return new Date(
Math.round(date.getTime() / ms) * ms
)
}
floor, ceil,
trunc;import { roundToNearestMinutes } from 'date-fns'
const date = new Date(2025, 3, 10, 12, 58)
const result = roundToNearestMinutes(date, {
nearestTo: 5
})
console.log(result)
Результат:
13:00
import { roundToNearestMinutes } from 'date-fns'
const date = new Date(2025, 3, 10, 23, 58)
const result = roundToNearestMinutes(date, {
nearestTo: 5
})
console.log(result)
Результат:
00:00 следующего дня
roundToNearestMinutes(date, {
nearestTo: 15
})
roundToNearestMinutes(date, {
nearestTo: 1
})
roundToNearestMinutes(date, {
nearestTo: 30
})
roundToNearestMinutes(date, {
nearestTo: 10
})
date-fnsaddMinutesimport {
roundToNearestMinutes,
addMinutes
} from 'date-fns'
const rounded = roundToNearestMinutes(
new Date(),
{
nearestTo: 15
}
)
const next = addMinutes(rounded, 15)
console.log(next)
isBeforeimport {
roundToNearestMinutes,
isBefore
} from 'date-fns'
const rounded = roundToNearestMinutes(
new Date(),
{
nearestTo: 5
}
)
const lim it = new Date(2025, 3, 10, 18, 0)
console.log(
isBefore(rounded, lim it)
)
Функция выполняет:
Date.Операция очень быстрая и подходит даже для обработки больших массивов дат.
nearestTo: 60
Ошибка:
RangeError
roundToNearestMinutes('2025-01-01')
Результат может быть некорректным.
Корректный вариант:
roundToNearestMinutes(
new Date('2025-01-01')
)
roundingMethodРазные методы дают разный результат.
roundingMethod: 'floor'
и
roundingMethod: 'ceil'
могут возвращать противоположные значения.
import {
roundToNearestMinutes,
addMinutes,
format
} from 'date-fns'
function getDeliverySlot(date) {
const rounded = roundToNearestMinutes(date, {
nearestTo: 30,
roundingMethod: 'ceil'
})
return addMinutes(rounded, 30)
}
const slot = getDeliverySlot(new Date())
console.log(
format(slot, 'HH:mm')
)
import {
roundToNearestMinutes,
format
} from 'date-fns'
const logs = [
new Date(2025, 3, 10, 12, 1),
new Date(2025, 3, 10, 12, 3),
new Date(2025, 3, 10, 12, 7)
]
const grouped = {}
for (const log of logs) {
const rounded = roundToNearestMinutes(log, {
nearestTo: 5
})
const key = format(rounded, 'HH:mm')
grouped[key] = (grouped[key] || 0) + 1
}
console.log(grouped)
Результат:
{
'12:00': 1,
'12:05': 2
}