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

Commit

Permalink
feat(timeSince): time elapsed since in xx days/hours/minutes ago form…
Browse files Browse the repository at this point in the history
…at (#217)
  • Loading branch information
sumdook authored and Kent C. Dodds committed Jan 3, 2019
1 parent 5dc0c8d commit e876550
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ import descendingOrder from './descending-order'
import reduceCount from './reduceCount'
import BitwiseAnd from './BitwiseAnd'
import copyArrayByValue from './copyArrayByValue'
import timeSince from './timeSince'

export {
reverseArrayInPlace,
Expand Down Expand Up @@ -164,4 +165,5 @@ export {
reduceCount,
BitwiseAnd,
copyArrayByValue,
timeSince,
}
25 changes: 25 additions & 0 deletions src/timeSince.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
export default timeSince

/**
* This method will return time ellapse since in "xxxx days/hours/mins/seconds ago" format.
* Inspired by: https://stackoverflow.com/a/3177838/8301717
* @param {Date} date - The date object
* @return {String} - Formatted time
*/

function timeSince(date) {
const seconds = Math.floor((new Date() - date) / 1000)
let interval = Math.floor(seconds / 86400)
if (interval > 1) {
return `${interval} days ago`
}
interval = Math.floor(seconds / 3600)
if (interval > 1) {
return `${interval} hours ago`
}
interval = Math.floor(seconds / 60)
if (interval > 1) {
return `${interval} minutes ago`
}
return `${Math.floor(seconds)} seconds ago`
}
31 changes: 31 additions & 0 deletions test/timeSince.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import test from 'ava'
import {timeSince} from '../src'

test('Changes date to days ago format', t => {
const aDay = 2 * 24 * 60 * 60 * 1000
const expected = '2 days ago'
const actual = timeSince(new Date(Date.now() - aDay))
t.deepEqual(actual, expected)
})

test('Changes date to hours ago format', t => {
const threeHours = 3 * 60 * 60 * 1000
const expected = '3 hours ago'
const actual = timeSince(new Date(Date.now() - threeHours))
t.deepEqual(actual, expected)
})


test('Changes date to minute ago format', t => {
const fourMinutes = 4 * 60 * 1000
const expected = '4 minutes ago'
const actual = timeSince(new Date(Date.now() - fourMinutes))
t.deepEqual(actual, expected)
})

test('Changes date to seconds ago format', t => {
const fiveSeconds = 5 * 1000
const expected = '5 seconds ago'
const actual = timeSince(new Date(Date.now() - fiveSeconds))
t.deepEqual(actual, expected)
})

0 comments on commit e876550

Please sign in to comment.