Created
March 5, 2020 15:06
-
-
Save alizadeh118/8bf6c95cb71cc3762b8e8e1a33d92a42 to your computer and use it in GitHub Desktop.
Decompose second to time units
This file contains hidden or 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
function timeDecompose(s, toString) { | |
toString = Boolean(toString) || false; | |
s = Number(s); | |
var time = {}; | |
time.year = Math.floor(s / 3.154e7); | |
time.month = Math.floor(s % 3.154e7 / 2.628e6); | |
time.day = Math.floor(s % 3.154e7 % 2.628e6 / 86400); | |
time.hour = Math.floor(s % 3.154e7 % 2.628e6 % 86400 / 3600); | |
time.minute = Math.floor(s % 3.154e7 % 2.628e6 % 86400 % 3600 / 60); | |
time.second = Math.floor(s % 3.154e7 % 2.628e6 % 86400 % 3600 % 60); | |
if (toString) { | |
var output = ''; | |
for (var unit in time) { | |
if (time[unit]) { | |
output += time[unit]; | |
output += ' ' + unit; | |
if (time[unit] > 1) | |
output += 's'; | |
output += ' and '; | |
} | |
} | |
output = output.replace(/ and $/, ''); | |
return output; | |
} | |
return time; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
timeDecompose
Decompose seconds to time units using
timeDecompose
.Usage
timeDecompose
accepts two parameters.true
returns human-readable String, otherwise and as default returns an Object.Examples
Calculate the age: