From 7ee545f17ddf2032df2d2c45f3a9e93d17e5e1ae Mon Sep 17 00:00:00 2001 From: Vesa Luusua Date: Wed, 19 Jun 2019 17:09:51 +0300 Subject: [PATCH] Add minutesBetween utility function --- src/util/dates.js | 17 +++++++++++++++++ src/util/dates.test.js | 23 +++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/src/util/dates.js b/src/util/dates.js index e8705974..5599df18 100644 --- a/src/util/dates.js +++ b/src/util/dates.js @@ -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 * diff --git a/src/util/dates.test.js b/src/util/dates.test.js index daab97c2..312e8e09 100644 --- a/src/util/dates.test.js +++ b/src/util/dates.test.js @@ -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