Add minutesBetween utility function

This commit is contained in:
Vesa Luusua 2019-06-19 17:09:51 +03:00
parent e3852a2b20
commit 7ee545f17d
2 changed files with 40 additions and 0 deletions

View file

@ -114,6 +114,23 @@ export const daysBetween = (startDate, endDate) => {
return days;
};
/**
* Calculate the number of minutes between the given dates
*
* @param {Date} startDate start of the time period
* @param {Date} endDate end of the time period.
*
* @throws Will throw if the end date is before the start date
* @returns {Number} number of minutes between the given Date objects
*/
export const minutesBetween = (startDate, endDate) => {
const minutes = moment(endDate).diff(startDate, 'minutes');
if (minutes < 0) {
throw new Error('End Date cannot be before start Date');
}
return minutes;
};
/**
* Format the given date to month id/string
*

View file

@ -4,6 +4,7 @@ import {
isSameDate,
nightsBetween,
daysBetween,
minutesBetween,
formatDate,
parseDateFromISO8601,
stringifyDateToISO8601,
@ -80,6 +81,28 @@ describe('date utils', () => {
});
});
describe('minutesBetween()', () => {
it('should fail if end Date is before start Date', () => {
const start = new Date(2017, 0, 2);
const end = new Date(2017, 0, 1);
expect(() => minutesBetween(start, end)).toThrow('End Date cannot be before start Date');
});
it('should handle equal start and end Dates', () => {
const d = new Date(2017, 0, 1, 10, 35, 0);
expect(minutesBetween(d, d)).toEqual(0);
});
it('should calculate minutes count for one hour', () => {
const start = new Date(2017, 0, 1, 10, 35, 0);
const end = new Date(2017, 0, 1, 11, 35, 0);
expect(minutesBetween(start, end)).toEqual(60);
});
it('should calculate minutes', () => {
const start = new Date(2017, 0, 1, 10, 35, 0);
const end = new Date(2017, 0, 1, 10, 55, 0);
expect(minutesBetween(start, end)).toEqual(20);
});
});
describe('formatDate()', () => {
/*
NOTE: These are not really testing the formatting properly since