Last active
September 7, 2024 09:53
-
-
Save PantheraRed/2e65c48cdfa6fba49473913300cc8b12 to your computer and use it in GitHub Desktop.
Convert milliseconds to years, months, days, hours, minutes & seconds in JavaScript.
This file contains 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
'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 } |
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
@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.