Javascript: Get Date Difference And Convert Months To Years
If given two dates in the MM/YY format how can I get the difference in years and months alone using a function. Example: the result of 03/10 & 01/14 would be 3 years and 10 mon
Solution 1:
I would highly recommend momentjs for date manipulation in JavaScript.
var start = moment("03/10", "MM/YY"),
finish = moment("01/14", "MM/YY");
var diff = finish.diff(start),
duration = moment.duration(diff);
duration.years(); // 3
duration.months(); // 10
Enjoy momentjs. It makes your life so easy.
Solution 2:
You could parse the date and calculate it with milliseconds, but this is a quicker way.
var date1 = "03/10".split("/");
var date2 = "01/14".split("/");
var months = date2[0] - date1[0] + 12 * (date2[1] - date1[1]);
var result = Math.round(months / 12) + " years " + (months % 12) + " months";
You can swap the date strings on the first 2 lines with your variables, and you should be able to guess where you get the years and months out as numbers.
Post a Comment for "Javascript: Get Date Difference And Convert Months To Years"