Skip to content

Instantly share code, notes, and snippets.

@alizadeh118
Created March 5, 2020 15:06
Show Gist options
  • Save alizadeh118/8bf6c95cb71cc3762b8e8e1a33d92a42 to your computer and use it in GitHub Desktop.
Save alizadeh118/8bf6c95cb71cc3762b8e8e1a33d92a42 to your computer and use it in GitHub Desktop.
Decompose second to time units
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;
}
@alizadeh118
Copy link
Author

timeDecompose

Decompose seconds to time units using timeDecompose.

Usage

timeDecompose accepts two parameters.

  1. (Number) Seconds want to decompose.
  2. (Boolean) true returns human-readable String, otherwise and as default returns an Object.

Examples

timeDecompose(123456789);
// { year: 3, month: 10, day: 29, hour: 14, minute: 13, second: 9 }

timeDecompose(123456789, true);
// "3 years and 10 months and 29 days and 14 hours and 13 minutes and 9 seconds"

Calculate the age:

var today = new Date();
var birthdate = new Date(1993, 3, 21, 18) // March 21, 1993 at 6 PM

// getTime() will get the date in milliseconds, so divide by 1000:
var seconds = (today.getTime() - birthdate.getTime()) / 1000;

timeDecompose(seconds, true);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment