将天数转换为年,月,日 [英] Convert number of days into years, months, days

查看:198
本文介绍了将天数转换为年,月,日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个日期选择器,用于计算两个日期之间的天数.目前,我正在输出天数(请参见下面的代码),这是毫无意义的.我想以年,月,日为单位输出该数字.我该怎么办?

I have two date pickers that calculates the number of days there are between the two dates. At the moment I'm outputting the number of days (see code below) which is kind of meaningless. I want to output that number in years, months, days. How can I do that?

例如,从01/01/14到2015年1月2日= 397天,则变为1年,1个月,1天

E.g So 01/01/14 to 01/02/15 = 397 days which then becomes 1 year(s), 1 month(s), 1 day(s)

var diff = endDate - startDate;
dayCount = diff / ( 60 * 60 * 24 * 1000 ); // secs * mins * hours * milliseconds
dayCount = Math.round( dayCount ) + this.options.countAdjust;
return dayCount;

推荐答案

您的计算中存在错误: 这是0个月. 如果你的意思是d/m/y 1 year, 1 month, and 0 day old.

You have a bug in your calculation : it's 0 month. And if you mean d/m/y then 1 year, 1 month, and 0 day old.

您在两个日期之间说了 (不包括)-

you said between the two dates ( not include) - look here

无论如何,这是正确的代码,其中包括每个月的实际计数-它有多少天! (leap年考虑):

Anyway here is the right code which include actually count each month - how many days it has ! ( leap year consideration):

注意:

我将其实例化为d/m/yyy.随时发送正确的模式:

I instantiated it as d/m/yyy. feel free to send right pattern in :

alert(getAge( new Date(2014,0,1),new Date(2015,0,2)))

function getAge(date_1, date_2)
{
  
//convert to UTC
var date2_UTC = new Date(Date.UTC(date_2.getUTCFullYear(), date_2.getUTCMonth(), date_2.getUTCDate()));
var date1_UTC = new Date(Date.UTC(date_1.getUTCFullYear(), date_1.getUTCMonth(), date_1.getUTCDate()));


var yAppendix, mAppendix, dAppendix;


//--------------------------------------------------------------
var days = date2_UTC.getDate() - date1_UTC.getDate();
if (days < 0)
{

    date2_UTC.setMonth(date2_UTC.getMonth() - 1);
    days += DaysInMonth(date2_UTC);
}
//--------------------------------------------------------------
var months = date2_UTC.getMonth() - date1_UTC.getMonth();
if (months < 0)
{
    date2_UTC.setFullYear(date2_UTC.getFullYear() - 1);
    months += 12;
}
//--------------------------------------------------------------
var years = date2_UTC.getFullYear() - date1_UTC.getFullYear();




if (years > 1) yAppendix = " years";
else yAppendix = " year";
if (months > 1) mAppendix = " months";
else mAppendix = " month";
if (days > 1) dAppendix = " days";
else dAppendix = " day";


return years + yAppendix + ", " + months + mAppendix + ", and " + days + dAppendix + " old.";
}


function DaysInMonth(date2_UTC)
{
var monthStart = new Date(date2_UTC.getFullYear(), date2_UTC.getMonth(), 1);
var monthEnd = new Date(date2_UTC.getFullYear(), date2_UTC.getMonth() + 1, 1);
var monthLength = (monthEnd - monthStart) / (1000 * 60 * 60 * 24);
return monthLength;
}


alert(getAge(new Date(2014, 0, 1), new Date(2015, 1, 1)))

这篇关于将天数转换为年,月,日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆