Skip to content

Commit 337155f

Browse files
committed
edge case with milliseconds
1 parent 1e39b68 commit 337155f

File tree

2 files changed

+30
-11
lines changed

2 files changed

+30
-11
lines changed

src/roundToNearestMinutes/index.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,9 @@ export default function roundToNearestMinutes<DateType extends Date>(
6262
}
6363

6464
const date = toDate(dirtyDate)
65-
const seconds = date.getSeconds() // relevant if nearestTo is 1, which is the default case
66-
const minutes = date.getMinutes() + seconds / 60
65+
const fractionalSeconds = date.getSeconds() / 60
66+
const fractionalMilliseconds = date.getMilliseconds() / 1000 / 60
67+
const minutes = date.getMinutes() + fractionalSeconds + fractionalMilliseconds
6768

6869
// Unlike the `differenceIn*` functions, the default rounding behavior is `round` and not 'trunc'
6970
const method = options?.roundingMethod ?? 'round'

src/roundToNearestMinutes/test.ts

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,13 @@
33
import assert from 'assert'
44
import roundToNearestMinutes, { RoundToNearestMinutesOptions } from './index'
55

6-
function makeDate(minutes: number, seconds: number = 0) {
6+
function makeDate(
7+
minutes: number,
8+
seconds: number = 0,
9+
milliseconds: number = 0
10+
) {
711
// helper to make tests more readable since we mostly care about minutes and seconds
8-
return new Date(2014, 6 /* Jul */, 10, 12, minutes, seconds, 0)
12+
return new Date(2014, 6 /* Jul */, 10, 12, minutes, seconds, milliseconds)
913
}
1014

1115
describe('roundToNearestMinutes', () => {
@@ -51,13 +55,6 @@ describe('roundToNearestMinutes', () => {
5155
)
5256
})
5357

54-
it('rounds up to the next day', () => {
55-
assert.deepStrictEqual(
56-
roundToNearestMinutes(new Date(2014, 6, 10, 23, 59, 59)),
57-
new Date(2014, 6, 11)
58-
)
59-
})
60-
6158
describe('roundingMethod', () => {
6259
it('trunc, nearestTo === 1 (default)', () => {
6360
const options: RoundToNearestMinutesOptions = { roundingMethod: 'trunc' }
@@ -248,6 +245,27 @@ describe('roundToNearestMinutes', () => {
248245
})
249246
})
250247

248+
describe('edge cases', () => {
249+
it('rounds up to the next day', () => {
250+
assert.deepStrictEqual(
251+
roundToNearestMinutes(new Date(2014, 6, 10, 23, 59, 59)),
252+
new Date(2014, 6, 11)
253+
)
254+
})
255+
256+
it('ceils correctly with 0 seconds and 1 millisecond', () => {
257+
assert.deepStrictEqual(
258+
roundToNearestMinutes(makeDate(15, 0, 0), { roundingMethod: 'ceil' }),
259+
makeDate(15)
260+
)
261+
262+
assert.deepStrictEqual(
263+
roundToNearestMinutes(makeDate(15, 0, 1), { roundingMethod: 'ceil' }),
264+
makeDate(16)
265+
)
266+
})
267+
})
268+
251269
describe('examples', () => {
252270
it('example 1', () => {
253271
const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34))

0 commit comments

Comments
 (0)