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.
Asked
Active
Viewed 3,610 times
3
-
Possible duplicate of [Converting milliseconds to a date (jQuery/JS)](http://stackoverflow.com/questions/4673527/converting-milliseconds-to-a-date-jquery-js) – Yoplaboom Jul 13 '16 at 14:56
-
I thibk you can just pass it to the Date object as argumebt, then get the time – Bálint Jul 13 '16 at 14:57
-
The best you can do is be approximate, because the definition of a year/month is not static. There're leap years and months have different lengths. – 4castle Jul 13 '16 at 14:59
-
Given the description, it's more likely a duplicate of [Difference between two dates in years, months, days in JavaScript](http://stackoverflow.com/questions/17732897/difference-between-two-dates-in-years-months-days-in-javascript) – Arnauld Jul 13 '16 at 15:00
-
You could just use maths? E.g. `x/100 = y` (seconds), `y/60 = m` (minutes), `m/60 = h` (hrs), `h/24 = d` (days) etc.. (maths is probably way off, but you get the picture) – Gavin Thomas Jul 13 '16 at 15:01
-
depperm,I got the diference in miliseconds,now I need to covert the difference to y;m;d;m;s.For instance the user sets a Date , my program must show- from that date x years y months x minutes and etc have passed. – Armine Jul 13 '16 at 15:13
2 Answers
7
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);

4castle
- 32,613
- 11
- 69
- 106
1
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

shinobi
- 2,511
- 1
- 19
- 27