2017-05-09 58 views
-2

我需要计算日期,月份和年份两个日期之间的精确差异。使用javascript计算年,月和日?

我有这样的功能:

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年,如果是“生日”之前,则为5年)。

我需要它输出5年,11个月和29天(作为例子)。

我该如何做到这一点?

+2

一般来说我建议使用[Moment.js(https://momentjs.com/)如果如果您在日期上进行大量工作,则可能。它会让你得到[差异](https://momentjs.com/docs/#/displaying/difference/)并以任何你想要的方式设置这个持续时间的格式。 –

+2

一直在问这个问题。尝试在你问之前进行搜索。 –

回答

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}; 
}; 
+0

您应该将您的代码作为可运行代码段发布。请注意,OP的字符串格式是YYYY-MM-DD,它将被解析为UTC。您的代码会以YYYY/M/D格式生成并解析字符串,但可能根本无法正确解析,但可能与本地相同,因此会引入与主机时区偏移量相等的错误。为什么要构建一个字符串,并在可以直接将值赋给Date构造函数时依赖不可靠的解析? – RobG

+0

使用今天的日期给出了{{year:-1,months:-1,days:-1}}和2017-05-10上的'2016-05-11'给出了{{year:0,months:11,days :47}'。 – RobG

+0

我的不好,我编辑代码与替换,现在与'YYYY/MM/DD'和'YYYY-MM-DD' – willicab

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); 
+0

答案不应依赖OP中未标记或使用的库。 – RobG