-
-
Save jonkemp/1009446 to your computer and use it in GitHub Desktop.
Super small relative dates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = (function(){ | |
const MS = | |
{ seconds: 1000 | |
, minutes: 60 * 1000 | |
, hours: 60 * 60 * 1000 | |
, days: 24 * 60 * 60 * 1000 | |
, weeks: 7 * 24 * 60 * 60 * 1000 | |
, months: 30 * 7 * 24 * 60 * 60 * 1000 | |
, years: 365 * 24 * 60 * 60 * 1000 } | |
return ago | |
function ago ( origin ) { | |
var delta = Date.now() - origin.getTime() | |
, ago | |
if ( ago = doDelta( 'years') ) | |
return ~~ago + 'y' | |
else if ( ago = doDelta( 'months') ) | |
return ~~ago + 'm' | |
else if ( ago = doDelta( 'weeks') ) | |
return ~~ago + 'w' | |
else if ( ago = doDelta( 'days') ) | |
return ~~ago + 'd' | |
else if ( ago = doDelta( 'hours') ) | |
return ~~ago + 'h' | |
else if ( ago = doDelta( 'minutes') ) | |
return ~~ago + 'm' | |
else if ( ago = doDelta( 'seconds') ) | |
return ~~ago + 's' | |
return 'now' | |
function doDelta ( type ) { | |
var result = delta / MS[type] | |
return result >= 1 && result | |
} | |
} | |
})() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ago = require( './ago' ) | |
, now = new Date | |
console.log( ago( new Date( 2011, now.getMonth(), now.getDate(), now.getHours() - 5 ) ) ) // 5h | |
console.log( ago( new Date( 2011, now.getMonth(), now.getDate() - 15 ) ) ) // 2w | |
console.log( ago( new Date( 2006, now.getMonth(), now.getDate() ) ) ) // 5y |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment