Skip to content
This repository was archived by the owner on Feb 20, 2019. It is now read-only.

Commit 79b9e20

Browse files
rigobauerKent C. Dodds
authored andcommitted
feat(timeDifference): Add timeDifference function (#145)
1 parent 0bc6741 commit 79b9e20

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

src/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ import getOrdinalSuffix from './get-ordinal-suffix'
5050
import arrayAverage from './array-average'
5151
import find from './find'
5252
import median from './array-median'
53+
import timeDifference from './timeDifference'
5354

5455
export {
5556
isOdd,
@@ -104,4 +105,5 @@ export {
104105
getOrdinalSuffix,
105106
arrayAverage,
106107
median,
108+
timeDifference,
107109
}

src/timeDifference.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
export default timeDifference
2+
3+
/**
4+
* Original Source: https://stackoverflow.com/questions/46883149
5+
* This method will calculate the time difference
6+
* between two time values
7+
*
8+
* @param {String} startTime - string with the start time in hh:mm format
9+
* @param {String} endTime - string with the end time in hh:mm format
10+
* @return {String} - should return a string with the time difference in hh:mm format
11+
*/
12+
13+
function timeDifference(startTime, endTime) {
14+
15+
let hourDiff = ((new Date(`01/01/2018 ${endTime}`)) - (new Date(`01/01/2018 ${startTime}`))) / 60000
16+
let hours = 0
17+
let minutes = 0
18+
19+
// If difference is negative, add 24 hours
20+
hourDiff = (hourDiff < 0) ? hourDiff + 1440 : hourDiff
21+
22+
hours = Math.floor(hourDiff / 60)
23+
minutes = Math.floor(hourDiff % 60)
24+
25+
return `${hours < 10 ? `0${hours}` : hours}:${minutes < 10 ? `0${minutes}` : minutes}`
26+
}
27+
28+
29+

test/timeDifference.test.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import test from 'ava'
2+
import {timeDifference} from '../src'
3+
4+
test('time difference when startTime<endTime', t => {
5+
const startTime = '10:45'
6+
const endTime = '19:15'
7+
const expected = '08:30'
8+
const actual = timeDifference(startTime, endTime)
9+
t.is(actual, expected)
10+
})
11+
12+
test('time difference when startTime>endTime', t => {
13+
const startTime = '13:40'
14+
const endTime = '09:43'
15+
const expected = '20:03'
16+
const actual = timeDifference(startTime, endTime)
17+
t.is(actual, expected)
18+
})

0 commit comments

Comments
 (0)