Skip to content

Commit

Permalink
add JSDoc and tests for new date utils
Browse files Browse the repository at this point in the history
  • Loading branch information
lemming committed Sep 12, 2023
1 parent 3bdf133 commit 0ea56aa
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/date_utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -831,13 +831,34 @@ export function getHoursInDay(d) {
return Math.round((+startOfTheNextDay - +startOfDay) / 3_600_000);
}

/**
* Returns the start of the minute for the given date
*
* NOTE: this function is a DST and timezone-safe analog of `date-fns/startOfMinute`
* do not make changes unless you know what you're doing
*
* See comments on https://github.com/Hacker0x01/react-datepicker/pull/4244
* for more details
*
* @param {Date} d date
* @returns {Date} start of the minute
*/
export function startOfMinute(d) {
const seconds = d.getSeconds();
const milliseconds = d.getMilliseconds();

return toDate(d.getTime() - seconds * 1000 - milliseconds);
}

/**
* Returns whether the given dates are in the same minute
*
* This function is a DST and timezone-safe analog of `date-fns/isSameMinute`
*
* @param {Date} d1
* @param {Date} d2
* @returns {boolean}
*/
export function isSameMinute(d1, d2) {
return startOfMinute(d1).getTime() === startOfMinute(d2).getTime();
}
25 changes: 25 additions & 0 deletions test/date_utils_test.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
addDays,
subDays,
isEqual,
isSameMinute,
isSameDay,
isSameMonth,
isSameQuarter,
Expand Down Expand Up @@ -37,6 +38,7 @@ import {
safeDateRangeFormat,
getHolidaysMap,
arraysAreEqual,
startOfMinute,
} from "../src/date_utils";
import setMinutes from "date-fns/setMinutes";
import setHours from "date-fns/setHours";
Expand Down Expand Up @@ -1223,4 +1225,27 @@ describe("date_utils", () => {
expect(arraysAreEqual(array1, array2)).toBe(false);
});
});

describe("isSameMinute", () => {
it("should return true if two dates are within the same minute", () => {
const d1 = new Date(2020, 10, 10, 10, 10, 10); // Nov 10, 2020 10:10:10
const d2 = new Date(2020, 10, 10, 10, 10, 20); // Nov 10, 2020 10:10:20
expect(isSameMinute(d1, d2)).toBe(true);
});

it("should return false if two dates aren't within the same minute", () => {
const d1 = new Date(2020, 10, 10, 10, 10, 10); // Nov 10, 2020 10:10:10
const d2 = new Date(2020, 10, 10, 10, 11, 10); // Nov 10, 2020 10:11:10
expect(isSameMinute(d1, d2)).toBe(false);
});
});

describe("startOfMinute", () => {
it("should properly find the start of the minute", () => {
const d = new Date(2020, 10, 10, 10, 10, 10); // Nov 10, 2020 10:10:10
const expected = new Date(2020, 10, 10, 10, 10, 0); // Nov 10, 2020 10:10:00

expect(startOfMinute(d)).toEqual(expected);
});
});
});

0 comments on commit 0ea56aa

Please sign in to comment.