Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/469.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何计算两个日期之间的年数?_Javascript_Datetime - Fatal编程技术网

Javascript 如何计算两个日期之间的年数?

Javascript 如何计算两个日期之间的年数?,javascript,datetime,Javascript,Datetime,我想得到两个日期之间的年数。我可以得到这两天之间的天数,但是如果我把它除以365,结果是不正确的,因为有些年份有366天 这是我获取日期差异的代码: var birthday = value;//format 01/02/1900 var dateParts = birthday.split("/"); var checkindate = new Date(dateParts[2], dateParts[0] - 1, dateParts[1]); var now = new Date(

我想得到两个日期之间的年数。我可以得到这两天之间的天数,但是如果我把它除以365,结果是不正确的,因为有些年份有366天

这是我获取日期差异的代码:

var birthday = value;//format 01/02/1900
var dateParts = birthday.split("/");

var checkindate = new Date(dateParts[2], dateParts[0] - 1, dateParts[1]);   
var now = new Date();
var difference = now - checkindate;
var days = difference / (1000*60*60*24);

var thisyear = new Date().getFullYear();
var birthyear = dateParts[2];

    var number_of_long_years = 0;
for(var y=birthyear; y <= thisyear; y++){   

    if( (y % 4 == 0 && y % 100 == 0) || y % 400 == 0 ) {

                    number_of_long_years++;             
    }
}   

我正在计算年份。这是正确的,还是有更好的方法呢?

可能不是你想要的答案,但2.6kb的内存,我不会尝试重新发明轮子,我会使用类似的方法。没有任何依赖项


diff
方法可能就是您想要的:

for(var y=birthyear;y每个循环不需要,不需要额外的jQuery插件…只需调用下面的函数..从


光滑基础JavaScript函数.< /P>

 function calculateAge(birthday) { // birthday is a date
   var ageDifMs = Date.now() - birthday;
   var ageDate = new Date(ageDifMs); // miliseconds from epoch
   return Math.abs(ageDate.getUTCFullYear() - 1970);
 }
这个能帮你。。。
通过的日期计算工作。您必须取两年中的1月1日。然后将公历日期转换为朱利安日数,然后取差值。

有点过时,但这里有一个函数您可以使用

function calculateAge(birthMonth, birthDay, birthYear) {
    var currentDate = new Date();
    var currentYear = currentDate.getFullYear();
    var currentMonth = currentDate.getMonth();
    var currentDay = currentDate.getDate(); 
    var calculatedAge = currentYear - birthYear;

    if (currentMonth < birthMonth - 1) {
        calculatedAge--;
    }
    if (birthMonth - 1 == currentMonth && currentDay < birthDay) {
        calculatedAge--;
    }
    return calculatedAge;
}

var age = calculateAge(12, 8, 1993);
alert(age);
函数calculateAge(生日、生日、生日){
var currentDate=新日期();
var currentYear=currentDate.getFullYear();
var currentMonth=currentDate.getMonth();
var currentDay=currentDate.getDate();
var calculatedAge=当前年份-出生年份;
如果(当前月<出生月-1){
计算年龄--;
}
如果(生日月-1==当前月和当前日<生日){
计算年龄--;
}
返回计算日期;
}
变量年龄=计算年龄(12,81993);
警觉(年龄);

我使用以下公式计算年龄

我将其命名为
gregorianAge()
,因为这种计算方法准确地给出了我们如何使用公历表示年龄。也就是说,如果月份和日期早于出生年份的月份和日期,则不计算结束年份

/**
*计算给定出生日期的人的年龄(以年为单位)。可选ageAtDate
*可用于计算特定日期的年龄
*
*@param string |日期对象生日
*@param string |日期对象ageAtDate可选
*@返回生日和给定日期或今天之间的整数年龄
*/
gregorianAge=函数(生日,ageAtDate){
//将出生日期转换为日期对象(如果尚未转换)
if(Object.prototype.toString.call(birthDate)!=='[Object Date]')
生日=新日期(生日);
//如果未提供ageAtDate,请使用今天的日期
如果(年龄日期的类型==“未定义”)
ageAtDate=新日期();
//将ageAtDate转换为日期对象(如果尚未转换)
else if(Object.prototype.toString.call(ageAtDate)!='[Object Date]')
ageAtDate=新日期(ageAtDate);
//如果转换为日期对象失败,则返回null
如果(年龄==null | |出生日期==null)
返回null;
var_m=ageAtDate.getMonth()-birthDate.getMonth();
//回答:岁减去出生年份减去一(1)个月和一天
//年龄在出生年份的月份和日期之前
return(ageAtDate.getFullYear())-birthDate.getFullYear()
-(_m<0 | |(_m==0&&ageAtDate.getDate()

以可接受的格式输入日期,例如2001年12月10日
我的年龄是多少?
是的,这很适合:

var moment = require('moment');
var startDate = new Date();
var endDate = new Date();
endDate.setDate(endDate.getFullYear() + 5); // Add 5 years to second date
console.log(moment.duration(endDate - startDate).years()); // This should returns 5

也许我的函数可以更好地解释如何在没有循环、计算和/或LIB的情况下以简单的方式实现这一点

功能检查年份差异(生日日期){
var todayDate=新日期();
var thisMonth=todayDate.getMonth();
var thiswear=todayDate.getFullYear();
var thisDay=todayDate.getDate();
var monthBirthday=birthday.getMonth();
var yearbirth=birthDayDate.getFullYear();
var daydearth=birthDayDate.getDate();
//首先,要区分年份
var yearDifference=今年-年生日;
//然后检查几个月
如果(本月==每月第一天){
//如果月份相同,则检查天数

如果(thisDay使用纯javascript
Date()
,我们可以像下面这样计算年份数

document.getElementById('getYearsBtn').addEventListener('click',函数(){
var enteredDate=document.getElementById('sampleDate')。值;
//下面一行是计算年数的单行逻辑。。。
变量年份=新日期(新日期()-新日期(输入日期)).getFullYear()-1970;
对数(年);
});

格式:yyyy-mm-dd或yyyy/mm/dd

计算年份
您可以使用TimeStamp获得确切的年龄:

const getAge = (dateOfBirth, dateToCalculate = new Date()) => {
    const dob = new Date(dateOfBirth).getTime();
    const dateToCompare = new Date(dateToCalculate).getTime();
    const age = (dateToCompare - dob) / (365 * 24 * 60 * 60 * 1000);
    return Math.floor(age);
};
getAge(月、日、年){
让Dearneow=新日期().getFullYear();
设monthNow=newdate().getMonth()+1;
让dayNow=new Date().getDate();
如果(monthNow==月和日现在<日| | monthNow<月){
回归渴望-第1年;
}否则{
回归渴望年;
}
}

如果有人需要浮动格式的利息计算年度

function floatYearDiff(olddate, newdate) {
  var new_y = newdate.getFullYear();
  var old_y = olddate.getFullYear();
  var diff_y = new_y - old_y;
  var start_year = new Date(olddate);
  var end_year = new Date(olddate);
  start_year.setFullYear(new_y);
  end_year.setFullYear(new_y+1);
  if (start_year > newdate) {
    start_year.setFullYear(new_y-1);
    end_year.setFullYear(new_y);
    diff_y--;
  }
  var diff = diff_y + (newdate - start_year)/(end_year - start_year);
  return diff;
}

如果你用的是瞬间

/**
 * Convert date of birth into age
 * param {string} dateOfBirth - date of birth
 * param {string} dateToCalculate  -  date to compare
 * returns {number} - age
 */
function getAge(dateOfBirth, dateToCalculate) {
    const dob = moment(dateOfBirth);
    return moment(dateToCalculate).diff(dob, 'years');
};

兄弟,moment.js在这方面非常棒: diff方法就是您想要的:

下面的函数返回从年份到当前年份的年份数组

const getYears=(from=2017)=>{
const diff=moment(new Date()).diff(new Date(`01/01/${from}`),years');
返回[…数组(diff>=0?diff+1:0).keys()].map((num)=>{
从+num返回;
});
}
console.log(getYears(2016));
获取年份(日期1、日期2){
让years=新日期(date1.getFullYear()-新日期(date2.getFullYear();
let month=新日期(date1).getMonth()-新日期(date2).getMonth();
让dateDiff=新日期(date1.getDay()-新日期(date2.getDay();
如果(日期差<0){
月份-=1;
}
如果(月<0){
年-=1年;
}
回归年;
}

这行得通吗?如果使用moment/***将出生日期转换为年龄*参数{string}dateOfBirth-出生日期*参数{string}dateToCalculate-要比较的日期*返回{number}-age*/导出常量getAge=(dateOfBirth,dateToCalc
var moment = require('moment');
var startDate = new Date();
var endDate = new Date();
endDate.setDate(endDate.getFullYear() + 5); // Add 5 years to second date
console.log(moment.duration(endDate - startDate).years()); // This should returns 5
function getYearDiff(startDate, endDate) {
    let yearDiff = endDate.getFullYear() - startDate.getFullYear();
    if (startDate.getMonth() > endDate.getMonth()) {
        yearDiff--;
    } else if (startDate.getMonth() === endDate.getMonth()) {
        if (startDate.getDate() > endDate.getDate()) {
            yearDiff--;
        } else if (startDate.getDate() === endDate.getDate()) {
            if (startDate.getHours() > endDate.getHours()) {
                yearDiff--;
            } else if (startDate.getHours() === endDate.getHours()) {
                if (startDate.getMinutes() > endDate.getMinutes()) {
                    yearDiff--;
                }
            }
        }
    }
    return yearDiff;
}

alert(getYearDiff(firstDate, secondDate));
const getAge = (dateOfBirth, dateToCalculate = new Date()) => {
    const dob = new Date(dateOfBirth).getTime();
    const dateToCompare = new Date(dateToCalculate).getTime();
    const age = (dateToCompare - dob) / (365 * 24 * 60 * 60 * 1000);
    return Math.floor(age);
};
getAge(month, day, year) {
    let yearNow = new Date().getFullYear();
    let monthNow = new Date().getMonth() + 1;
    let dayNow = new Date().getDate();
    if (monthNow === month && dayNow < day || monthNow < month) {
      return yearNow - year - 1;
    } else {
      return yearNow - year;
    }
  }
function floatYearDiff(olddate, newdate) {
  var new_y = newdate.getFullYear();
  var old_y = olddate.getFullYear();
  var diff_y = new_y - old_y;
  var start_year = new Date(olddate);
  var end_year = new Date(olddate);
  start_year.setFullYear(new_y);
  end_year.setFullYear(new_y+1);
  if (start_year > newdate) {
    start_year.setFullYear(new_y-1);
    end_year.setFullYear(new_y);
    diff_y--;
  }
  var diff = diff_y + (newdate - start_year)/(end_year - start_year);
  return diff;
}
/**
 * Convert date of birth into age
 * param {string} dateOfBirth - date of birth
 * param {string} dateToCalculate  -  date to compare
 * returns {number} - age
 */
function getAge(dateOfBirth, dateToCalculate) {
    const dob = moment(dateOfBirth);
    return moment(dateToCalculate).diff(dob, 'years');
};
let currentTime = new Date().getTime();
let birthDateTime= new Date(birthDate).getTime();
let difference = (currentTime - birthDateTime)
var ageInYears=difference/(1000*60*60*24*365)
getYears(date1, date2) {
let years = new Date(date1).getFullYear() - new Date(date2).getFullYear();
let month = new Date(date1).getMonth() - new Date(date2).getMonth();
let dateDiff = new Date(date1).getDay() - new Date(date2).getDay();
if (dateDiff < 0) {
    month -= 1;
}
if (month < 0) {
    years -= 1;
}
return years;
}
function dateDiffYearsOnly( dateNew,dateOld) {
   function date2ymd(d){ w=new Date(d);return [w.getFullYear(),w.getMonth(),w.getDate()]}
   function ymd2N(y){return (((y[0]<<4)+y[1])<<5)+y[2]} // or 60 and 60 // or 13 and 32 // or 25 and 40 //// with ...
   function date2N(d){ return ymd2N(date2ymd(d))}

   return  (date2N(dateNew)-date2N(dateOld))>>9
}
dateDiffYearsOnly(Date.now(),new Date(Date.now()-7*366*24*3600*1000));
dateDiffYearsOnly(Date.now(),new Date(Date.now()-7*365*24*3600*1000))