Armine
Armine

Reputation: 115

Is there a method to convert miliseconds to years,months,days,minutes,seconds in JavaScript?

I am trying to compare 2 dates and represent the difference( converted to miliseconds) via years,months,days,minutes and seconds.I am new in JS,I looked up for a ready method to convert miliseconds to years,months,days, minutes, seconds but didn't find.Tell me please is there such method? If not how can I do that? Simply by dividing the difference and using reminder?Thank you in advance for help.

Upvotes: 3

Views: 4999

Answers (3)

ZouCeR
ZouCeR

Reputation: 11

Here is a solution similar to other answers but with a different approach, I started from years instead of millis, I think is more accurate this way.

    const date = new Date(startDate).getTime()
    const today = new Date().getTime()
    
    // 1000 millis => sec , 86400 sec => day , 365 day => year
    let years = (today - date) / (1000 * 86400 * 365)
    let months = (years - Math.floor(years)) * 12
    let days = (months - Math.floor(months)) * 30
    let hours = (days - Math.floor(days)) * 24
    let minutes = (hours - Math.floor(hours)) * 60
    let sec = (minutes - Math.floor(minutes)) * 60
    let milli = (sec - Math.floor(sec)) * 1000
    
    years = Math.floor(years)
    months = Math.floor(months)
    days = Math.floor(days)
    hours = Math.floor(hours)
    minutes = Math.floor(minutes)
    sec = Math.floor(sec)
    milli = Math.floor(milli)

Upvotes: 1

castletheperson
castletheperson

Reputation: 33516

Without having a calendar and knowing the input dates, the best you can do is be approximate.

Here is a script that shows the time elapsed since midnight last night.

var diff = Date.now() - Date.parse("July 13, 2016");

var seconds = Math.floor(diff / 1000),
    minutes = Math.floor(seconds / 60),
    hours   = Math.floor(minutes / 60),
    days    = Math.floor(hours / 24),
    months  = Math.floor(days / 30),
    years   = Math.floor(days / 365);

seconds %= 60;
minutes %= 60;
hours %= 24;
days %= 30;
months %= 12;

console.log("Years:", years);
console.log("Months:", months);
console.log("Days:", days);
console.log("Hours:", hours);
console.log("Minutes:", minutes);
console.log("Seconds:", seconds);

Upvotes: 9

shinobi
shinobi

Reputation: 2527

There is no inbuilt method to convert given millisecond to equivalent seconds, minutes, hours, days, months or years.

You will have to use math. Although you will only be able to convert accurately up to days. Months and years will vary as months are either 28, 29, 30 or 31 and there are leap years.

Consider having a look at http://momentjs.com/ before you write anything on your own, as you can do a lot more with this library like adding and subtracting days or hours etc

Upvotes: 1

Related Questions