This repository was archived by the owner on Feb 20, 2019. It is now read-only.
File tree Expand file tree Collapse file tree 3 files changed +58
-0
lines changed Expand file tree Collapse file tree 3 files changed +58
-0
lines changed Original file line number Diff line number Diff line change @@ -80,6 +80,7 @@ import descendingOrder from './descending-order'
80
80
import reduceCount from './reduceCount'
81
81
import BitwiseAnd from './BitwiseAnd'
82
82
import copyArrayByValue from './copyArrayByValue'
83
+ import timeSince from './timeSince'
83
84
84
85
export {
85
86
reverseArrayInPlace ,
@@ -164,4 +165,5 @@ export {
164
165
reduceCount ,
165
166
BitwiseAnd ,
166
167
copyArrayByValue ,
168
+ timeSince ,
167
169
}
Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ } )
You can’t perform that action at this time.
0 commit comments