UNPKG

@xstoudi/human-readable-time

Version:

Easily parse seconds to human readable time and hrt to seconds.

84 lines (59 loc) 1.98 kB
const SECONDS_IN = { year: 31536000, week: 604800, day: 86400, hour: 3600, minute: 60 } function secondsToHRT(seconds) { let hrt = '' const years = Math.floor(seconds / SECONDS_IN.year) seconds -= SECONDS_IN.year * years if (years > 0) hrt = `${hrt}${years}y ` const weeks = Math.floor(seconds / SECONDS_IN.week) seconds -= SECONDS_IN.week * weeks if (weeks > 0) hrt = `${hrt}${weeks}w ` const days = Math.floor(seconds / SECONDS_IN.day) seconds -= SECONDS_IN.day * days if (days > 0) hrt = `${hrt}${days}d ` const hours = Math.floor(seconds / SECONDS_IN.hour) seconds -= SECONDS_IN.hour * hours if (hours > 0) hrt = `${hrt}${hours}h ` const minutes = Math.floor(seconds / SECONDS_IN.minute) seconds -= SECONDS_IN.minute * minutes if (minutes > 0) hrt = `${hrt}${minutes}m ` if (seconds > 0) hrt = `${hrt}${seconds}s ` return hrt.trim() } function hrtToSeconds(hrt) { let totalSeconds = 0 hrt.split(' ').forEach(sHrt => { const yearIndex = sHrt.indexOf('y') if (yearIndex != -1) { totalSeconds += Number(sHrt.slice(0, yearIndex)) * SECONDS_IN.year } const weeksIndex = sHrt.indexOf('w') if (weeksIndex != -1) return totalSeconds += Number(sHrt.slice(0, weeksIndex)) * SECONDS_IN.week const daysIndex = sHrt.indexOf('d') if (daysIndex != -1) return totalSeconds += Number(sHrt.slice(0, daysIndex)) * SECONDS_IN.day const hoursIndex = sHrt.indexOf('h') if (hoursIndex != -1) return totalSeconds += Number(sHrt.slice(0, hoursIndex)) * SECONDS_IN.hour const minutesIndex = sHrt.indexOf('m') if (minutesIndex != -1) return totalSeconds += Number(sHrt.slice(0, minutesIndex)) * SECONDS_IN.minute const secondsIndex = sHrt.indexOf('s') if (secondsIndex != -1) return totalSeconds += Number(sHrt.slice(0, secondsIndex)) }) return totalSeconds } module.exports = { hrtToSeconds, secondsToHRT }