我需要计算两个日期之间的确切差异,包括天,月和年。
我有这个功能:
const getAge = (dateString) => {
const today = new Date();
const birthDate = new Date(dateString);
let age = today.getFullYear() - birthDate.getFullYear();
const m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age -= 1;
}
return age;
};
它收到YYYY-MM-DD格式的日期。此时它会输出一个确切的年数(6年,如果它在#34;生日和#34之前,则为5年)。
我需要它输出5年,11个月和29天(作为例子)。
我怎样才能做到这一点?
答案 0 :(得分:1)
对我来说最好的解决方案是使用mementjs https://momentjs.com库。
之后试试这个:
var d1= Date.parse("2017/05/08");
var d2= Date.parse("2015/07/15");
var m = moment(d1);
var years = m.diff(d2, 'years');
m.add(-years, 'years');
var months = m.diff(d2, 'months');
m.add(-months, 'months');
var days = m.diff(d2, 'days');
var result = {years: years, months: months, days: days};
console.log(result);
答案 1 :(得分:0)
也许这可以帮到你
const getAge = (dateString) => {
const today = new Date();
const birthDate = new Date(dateString.replace(/-/g, '/'));
const yearsLater = new Date((birthDate.getFullYear()+1)+"/"+(birthDate.getMonth()+1)+"/"+birthDate.getDate());
const monthsLater = new Date((birthDate.getFullYear())+"/"+(birthDate.getMonth()+2)+"/"+birthDate.getDate());
const daysLater = new Date((birthDate.getFullYear())+"/"+(birthDate.getMonth()+1)+"/"+(birthDate.getDate()+1));
years = Math.floor((today-birthDate)/(yearsLater-birthDate));
dateMonths = (today-birthDate)%(yearsLater-birthDate);
months = Math.floor(dateMonths / (monthsLater-birthDate));
dateDays = dateMonths % (monthsLater-birthDate);
days = Math.floor(dateDays / (daysLater-birthDate));
return {"years": years, "months": months, "days": days};
};