Skip to content

Instantly share code, notes, and snippets.

@PantheraRed
Last active September 7, 2024 09:53
Show Gist options
  • Save PantheraRed/2e65c48cdfa6fba49473913300cc8b12 to your computer and use it in GitHub Desktop.
Save PantheraRed/2e65c48cdfa6fba49473913300cc8b12 to your computer and use it in GitHub Desktop.
Convert milliseconds to years, months, days, hours, minutes & seconds in JavaScript.
'use strict'; // Remove this if you don't wish to use strict mode
function ms(t) {
let year,
month,
day,
hour,
minute,
second;
second = Math.floor(t / 1000);
minute = Math.floor(second / 60);
second = second % 60;
hour = Math.floor(minute / 60);
minute = minute % 60;
day = Math.floor(hour / 24);
hour = hour % 24;
month = Math.floor(day / 30);
day = day % 30;
year = Math.floor(month / 12);
month = month % 12;
return { year, month, day, hour, minute, second };
}
module.exports = ms;
// Usage: ms(1627297964704) returns { year: 52, month: 3, day: 24, hour: 11, minute: 12, second: 44 }
@PantheraRed
Copy link
Author

@Danger89 Thank you for such a great explanation. This will definitely help me improve the gist in future. I personally found luxon a better alternative.

@melroy89
Copy link

melroy89 commented Jan 6, 2023

As I stated in my explanation, I'm using Luxon now.

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