Skip to content

Instantly share code, notes, and snippets.

@pedrouid
Last active September 17, 2017 02:15
Show Gist options
  • Save pedrouid/9d383be275ab2d647cf48bc13382b879 to your computer and use it in GitHub Desktop.
Save pedrouid/9d383be275ab2d647cf48bc13382b879 to your computer and use it in GitHub Desktop.
Get Time Ago String
// Just run this file with node and give it a valid Javascript Date string or timestamp
// It will return the string with time ago it nomenclature given the timedifference
//
// @param {String} date [REQUIRED]
// @param {Boolean} short
// @param {string} current
//
// Author: Pedro Gomes | Github @gomesphoto | Twitter @gomesphoto
const nodeQuery = Number(process.argv[2])
const shortFormat = process.argv[3] || false
const currentDate = process.argv[4] || Date.now()
if (!nodeQuery) {
console.log('NO DATE QUERY PASSED!')
} else if (isNaN(nodeQuery)) {
console.log('DATE ')
}
const monthsLong = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
const monthsShort = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec']
const limits = [60000, 3600000, 86400000, 604800000, 1209600000]
const getTimeagoString = (date, short, current) => {
if (!date) return null
let _current = current || Date.now()
if (isNaN(_current)) {
const _currentObj = new Date(_current)
_current = _currentObj.getTime()
}
const _date = Number(date) ? Number(date) : date
const dateObj = new Date(_date)
const timestamp = dateObj.getTime()
const month = dateObj.getUTCMonth()
const day = dateObj.getUTCDate()
const diff = _current - timestamp
let string = short
? `${monthsShort[month]} ${day}`
: `${monthsLong[month]} ${day}`
if (diff < limits[0]) {
string = 'just now'
return string
} else if (diff < limits[1]) {
const timeDiff = Math.ceil(diff / limits[0])
string = short ? `${timeDiff} mins ago` : `${timeDiff} minutes ago`
return string
} else if (diff < limits[2]) {
const timeDiff = Math.ceil(diff / limits[1])
string = timeDiff === 1 ? `${timeDiff} hour ago` : `${timeDiff} hours ago`
return string
} else if (diff < limits[3]) {
const timeDiff = Math.ceil(diff / limits[2])
string = timeDiff === 1 ? `${timeDiff} day ago` : `${timeDiff} days ago`
return string
}
return string
}
let result = getTimeagoString(nodeQuery, shortFormat, currentDate)
console.log(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment