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

Commit e876550

Browse files
sumdookKent C. Dodds
authored andcommitted
feat(timeSince): time elapsed since in xx days/hours/minutes ago format (#217)
1 parent 5dc0c8d commit e876550

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed

src/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ import descendingOrder from './descending-order'
8080
import reduceCount from './reduceCount'
8181
import BitwiseAnd from './BitwiseAnd'
8282
import copyArrayByValue from './copyArrayByValue'
83+
import timeSince from './timeSince'
8384

8485
export {
8586
reverseArrayInPlace,
@@ -164,4 +165,5 @@ export {
164165
reduceCount,
165166
BitwiseAnd,
166167
copyArrayByValue,
168+
timeSince,
167169
}

src/timeSince.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
export default timeSince
2+
3+
/**
4+
* This method will return time ellapse since in "xxxx days/hours/mins/seconds ago" format.
5+
* Inspired by: https://stackoverflow.com/a/3177838/8301717
6+
* @param {Date} date - The date object
7+
* @return {String} - Formatted time
8+
*/
9+
10+
function timeSince(date) {
11+
const seconds = Math.floor((new Date() - date) / 1000)
12+
let interval = Math.floor(seconds / 86400)
13+
if (interval > 1) {
14+
return `${interval} days ago`
15+
}
16+
interval = Math.floor(seconds / 3600)
17+
if (interval > 1) {
18+
return `${interval} hours ago`
19+
}
20+
interval = Math.floor(seconds / 60)
21+
if (interval > 1) {
22+
return `${interval} minutes ago`
23+
}
24+
return `${Math.floor(seconds)} seconds ago`
25+
}

test/timeSince.test.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import test from 'ava'
2+
import {timeSince} from '../src'
3+
4+
test('Changes date to days ago format', t => {
5+
const aDay = 2 * 24 * 60 * 60 * 1000
6+
const expected = '2 days ago'
7+
const actual = timeSince(new Date(Date.now() - aDay))
8+
t.deepEqual(actual, expected)
9+
})
10+
11+
test('Changes date to hours ago format', t => {
12+
const threeHours = 3 * 60 * 60 * 1000
13+
const expected = '3 hours ago'
14+
const actual = timeSince(new Date(Date.now() - threeHours))
15+
t.deepEqual(actual, expected)
16+
})
17+
18+
19+
test('Changes date to minute ago format', t => {
20+
const fourMinutes = 4 * 60 * 1000
21+
const expected = '4 minutes ago'
22+
const actual = timeSince(new Date(Date.now() - fourMinutes))
23+
t.deepEqual(actual, expected)
24+
})
25+
26+
test('Changes date to seconds ago format', t => {
27+
const fiveSeconds = 5 * 1000
28+
const expected = '5 seconds ago'
29+
const actual = timeSince(new Date(Date.now() - fiveSeconds))
30+
t.deepEqual(actual, expected)
31+
})

0 commit comments

Comments
 (0)