Javascript 根据YYYYMMDD格式的出生日期计算年龄
给定YYYYMMDD格式的出生日期,我如何计算以年为单位的年龄?是否可以使用Javascript 根据YYYYMMDD格式的出生日期计算年龄,javascript,date,Javascript,Date,给定YYYYMMDD格式的出生日期,我如何计算以年为单位的年龄?是否可以使用Date()功能 我正在寻找比我现在使用的解决方案更好的解决方案: var-dob='19800810'; 风险年=数量(多个月的子项(0,4)); 变量月=数量(月数(4,2))-1; var日=数量(出生日期(6,2)); var today=新日期(); var age=today.getFullYear()-year; if(今天.getMonth()59) 多伊诺--; if(isLeap(birthDate
Date()
功能
我正在寻找比我现在使用的解决方案更好的解决方案:
var-dob='19800810';
风险年=数量(多个月的子项(0,4));
变量月=数量(月数(4,2))-1;
var日=数量(出生日期(6,2));
var today=新日期();
var age=today.getFullYear()-year;
if(今天.getMonth() 警觉(年龄)代码>不久前,我为此制作了一个函数:
function getAge(birthDate) {
var now = new Date();
function isLeap(year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
// days since the birthdate
var days = Math.floor((now.getTime() - birthDate.getTime())/1000/60/60/24);
var age = 0;
// iterate the years
for (var y = birthDate.getFullYear(); y <= now.getFullYear(); y++){
var daysInYear = isLeap(y) ? 366 : 365;
if (days >= daysInYear){
days -= daysInYear;
age++;
// increment the age only if there are available enough days for the year.
}
}
return age;
}
为了测试生日是否已经过去,我定义了一个helper函数Date.prototype.getDoY
,它有效地返回一年中的天数。其余的都是不言自明的
Date.prototype.getDoY = function() {
var onejan = new Date(this.getFullYear(), 0, 1);
return Math.floor(((this - onejan) / 86400000) + 1);
};
function getAge(birthDate) {
function isLeap(year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
var now = new Date(),
age = now.getFullYear() - birthDate.getFullYear(),
doyNow = now.getDoY(),
doyBirth = birthDate.getDoY();
// normalize day-of-year in leap years
if (isLeap(now.getFullYear()) && doyNow > 58 && doyBirth > 59)
doyNow--;
if (isLeap(birthDate.getFullYear()) && doyNow > 58 && doyBirth > 59)
doyBirth--;
if (doyNow <= doyBirth)
age--; // birthday not yet passed this year, so -1
return age;
};
var myBirth = new Date(2001, 6, 4);
console.log(getAge(myBirth));
Date.prototype.getDoY=function(){
var onejan=新日期(this.getFullYear(),0,1);
返回数学楼层(((this-onejan)/86400000)+1);
};
函数getAge(生日){
功能isLeap(年){
返回年份%4==0&(年份%100!=0 | |年份%400==0);
}
var now=新日期(),
age=now.getFullYear()-生日.getFullYear(),
doyNow=now.getDoY(),
doyBirth=birthDate.getDoY();
//将闰年中的日期正常化
if(isLeap(now.getFullYear())&&doyNow>58&&doyBirth>59)
多伊诺--;
if(isLeap(birthDate.getFullYear())&&doyNow>58&&doyBirth>59)
多伊伯斯--;
if(doyNowfunction age()
{
var birthdate=$j(“#birthdate”).val();//格式为“mm/dd/yyyy”
var senddate=$j(“#expireDate”).val();//格式为“mm/dd/yyyy”
var x=出生日期。拆分(“/”);
变量y=senddate.split(“/”);
var b天=x[1];
var b月=x[0];
var byear=x[2];
//警报(b天);
var sdays=y[1];
var smonths=y[0];
var syear=y[2];
//警报(星期四);
如果(星期四<星期四)
{
sdays=parseInt(sdays)+30;
smonths=parseInt(smonths)-1;
//警报(星期四);
var fdays=星期四-星期四;
//警报(星期五);
}
否则{
var fdays=星期四-星期四;
}
如果(月数<月数)
{
smonths=parseInt(smonths)+12;
syear=syear-1;
var fmonths=smonths-bmonths;
}
其他的
{
var fmonths=smonths-bmonths;
}
var fyear=syear-byear;
document.getElementById('patientAge')。值=fyear+'years'+fmonths+'months'+fdays+'days';
}
试试这个
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
函数getAge(日期字符串){
var today=新日期();
var birthDate=新日期(日期字符串);
var age=today.getFullYear()-birthDate.getFullYear();
var m=today.getMonth()-birthDate.getMonth();
如果(m<0 | |(m==0&&today.getDate()
我相信你的代码中唯一看起来粗糙的部分就是substr
部分
Fiddle:我只需要自己编写这个函数-接受的答案相当好,但IMO可以使用一些清理。这需要一个unix时间戳作为dob,因为这是我的要求,但可以很快适应使用字符串:
var getAge = function(dob) {
var measureDays = function(dateObj) {
return 31*dateObj.getMonth()+dateObj.getDate();
},
d = new Date(dob*1000),
now = new Date();
return now.getFullYear() - d.getFullYear() - (measureDays(now) < measureDays(d));
}
var getAge=函数(dob){
var measureDays=函数(dateObj){
返回31*dateObj.getMonth()+dateObj.getDate();
},
d=新日期(dob*1000),
现在=新日期();
立即返回.getFullYear()-d.getFullYear()-(measureDays(now)
注意,我在measureDays函数中使用了一个固定值31。计算所关心的只是“一年中的某一天”是时间戳的单调递增度量
如果使用javascript时间戳或字符串,显然您需要删除因子1000。这是我的解决方案,只需传入一个可解析的日期:
function getAge(birth) {
ageMS = Date.parse(Date()) - Date.parse(birth);
age = new Date();
age.setTime(ageMS);
ageYear = age.getFullYear() - 1970;
return ageYear;
// ageMonth = age.getMonth(); // Accurate calculation of the month part of the age
// ageDay = age.getDate(); // Approximate calculation of the day part of the age
}
我知道这是一个非常古老的线程,但我想在这个实现中,我写了寻找年龄,我相信这是更准确的
var getAge = function(year,month,date){
var today = new Date();
var dob = new Date();
dob.setFullYear(year);
dob.setMonth(month-1);
dob.setDate(date);
var timeDiff = today.valueOf() - dob.valueOf();
var milliInDay = 24*60*60*1000;
var noOfDays = timeDiff / milliInDay;
var daysInYear = 365.242;
return ( noOfDays / daysInYear ) ;
}
当然,您可以对其进行调整,以适应获取参数的其他格式。希望这有助于寻找更好的解决方案。替代解决方案,因为:
function calculateAgeInYears (date) {
var now = new Date();
var current_year = now.getFullYear();
var year_diff = current_year - date.getFullYear();
var birthday_this_year = new Date(current_year, date.getMonth(), date.getDate());
var has_had_birthday_this_year = (now >= birthday_this_year);
return has_had_birthday_this_year
? year_diff
: year_diff - 1;
}
我已经检查了之前展示的例子,它们并不是在所有情况下都有效,正因为如此,我自己制作了一个脚本。我测试了这个,它工作得非常完美
function getAge(birth) {
var today = new Date();
var curr_date = today.getDate();
var curr_month = today.getMonth() + 1;
var curr_year = today.getFullYear();
var pieces = birth.split('/');
var birth_date = pieces[0];
var birth_month = pieces[1];
var birth_year = pieces[2];
if (curr_month == birth_month && curr_date >= birth_date) return parseInt(curr_year-birth_year);
if (curr_month == birth_month && curr_date < birth_date) return parseInt(curr_year-birth_year-1);
if (curr_month > birth_month) return parseInt(curr_year-birth_year);
if (curr_month < birth_month) return parseInt(curr_year-birth_year-1);
}
var age = getAge('18/01/2011');
alert(age);
函数getAge(出生){
var today=新日期();
var curr_date=today.getDate();
var curr_month=today.getMonth()+1;
var curr_year=today.getFullYear();
var pieces=birth.split('/');
var出生日期=件[0];
var birth_month=件[1];
var出生年份=件[2];
如果(当前月份==出生月份和当前日期>=出生日期)返回parseInt(当前年份-出生年份);
如果(当前月份==出生月份和当前日期<出生日期)返回parseInt(当前年份出生年份-1);
如果(当前月份>出生月份)返回parseInt(当前年份-出生年份);
如果(当前月份<出生月份)返回parseInt(当前年份出生年份-1);
}
var age=getAge('18/01/2011');
警觉(年龄);
重要提示:此答案不能提供100%的准确答案,根据日期的不同,它会被关闭大约10-20个小时。
没有更好的解决方案(无论如何,在这些答案中都没有)
当然,我忍不住要接受挑战,制作一个比目前公认的解决方案更快、更短的生日计算器。
我的解决方案的要点是,数学运算速度很快,因此我们不使用分支,而使用javascript提供的日期模型来计算解决方案,而是使用奇妙的数学
答案是这样的,比naveen的快约65%,而且要短得多:
function calcAge(dateString) {
var birthday = +new Date(dateString);
return ~~((Date.now() - birthday) / (31557600000));
}
魔法数字:31557600000是24*3600*365.25*1000
这是一年的长度,一年的长度是365天6小时,也就是0.25天。最后,我给出了最终的ag
function getAge(birth) {
var today = new Date();
var curr_date = today.getDate();
var curr_month = today.getMonth() + 1;
var curr_year = today.getFullYear();
var pieces = birth.split('/');
var birth_date = pieces[0];
var birth_month = pieces[1];
var birth_year = pieces[2];
if (curr_month == birth_month && curr_date >= birth_date) return parseInt(curr_year-birth_year);
if (curr_month == birth_month && curr_date < birth_date) return parseInt(curr_year-birth_year-1);
if (curr_month > birth_month) return parseInt(curr_year-birth_year);
if (curr_month < birth_month) return parseInt(curr_year-birth_year-1);
}
var age = getAge('18/01/2011');
alert(age);
function getAge(dateString) {
var dates = dateString.split("-");
var d = new Date();
var userday = dates[0];
var usermonth = dates[1];
var useryear = dates[2];
var curday = d.getDate();
var curmonth = d.getMonth()+1;
var curyear = d.getFullYear();
var age = curyear - useryear;
if((curmonth < usermonth) || ( (curmonth == usermonth) && curday < userday )){
age--;
}
return age;
}
getAge('16-03-1989')
function calcAge(dateString) {
var birthday = +new Date(dateString);
return ~~((Date.now() - birthday) / (31557600000));
}
function _calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
/* The difference, in years, between NOW and 2012-05-07 */
moment().diff(moment('20120507', 'YYYYMMDD'), 'years')
function calculateAge(year, month, day) {
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var currentMonth = currentDate.getUTCMonth() + 1;
var currentDay = currentDate.getUTCDate();
// You need to treat the cases where the year, month or day hasn't arrived yet.
var age = currentYear - year;
if (currentMonth > month) {
return age;
} else {
if (currentDay >= day) {
return age;
} else {
age--;
return age;
}
}
}
// Int Age to Date as string YYY-mm-dd
function age_to_date(age)
{
try {
var d = new Date();
var new_d = '';
d.setFullYear(d.getFullYear() - Math.abs(age));
new_d = d.getFullYear() + '-' + d.getMonth() + '-' + d.getDate();
return new_d;
} catch(err) {
console.log(err.message);
}
}
// Date string (YYY-mm-dd) to Int age (years old)
function date_to_age(date)
{
try {
var today = new Date();
var d = new Date(date);
var year = today.getFullYear() - d.getFullYear();
var month = today.getMonth() - d.getMonth();
var day = today.getDate() - d.getDate();
var carry = 0;
if (year < 0)
return 0;
if (month <= 0 && day <= 0)
carry -= 1;
var age = parseInt(year);
age += carry;
return Math.abs(age);
} catch(err) {
console.log(err.message);
}
}
var calculateAge = function(dob) {
var days = function(date) {
return 31*date.getMonth() + date.getDate();
},
d = new Date(dob*1000),
now = new Date();
return now.getFullYear() - d.getFullYear() - ( measureDays(now) < measureDays(d));
}
//dob date dd/mm/yy
var d = 01/01/1990
//today
//date today string format
var today = new Date(); // i.e wed 04 may 2016 15:12:09 GMT
//todays year
var todayYear = today.getFullYear();
// today month
var todayMonth = today.getMonth();
//today date
var todayDate = today.getDate();
//dob
//dob parsed as date format
var dob = new Date(d);
// dob year
var dobYear = dob.getFullYear();
// dob month
var dobMonth = dob.getMonth();
//dob date
var dobDate = dob.getDate();
var yearsDiff = todayYear - dobYear ;
var age;
if ( todayMonth < dobMonth )
{
age = yearsDiff - 1;
}
else if ( todayMonth > dobMonth )
{
age = yearsDiff ;
}
else //if today month = dob month
{ if ( todayDate < dobDate )
{
age = yearsDiff - 1;
}
else
{
age = yearsDiff;
}
}
function age(dateString){
let birth = new Date(dateString);
let now = new Date();
let beforeBirth = ((() => {birth.setDate(now.getDate());birth.setMonth(now.getMonth()); return birth.getTime()})() < birth.getTime()) ? 0 : 1;
return now.getFullYear() - birth.getFullYear() - beforeBirth;
}
age('09/20/1981');
//35
age(403501000000)
//34
function calcularEdad(fecha) {
// Si la fecha es correcta, calculamos la edad
if (typeof fecha != "string" && fecha && esNumero(fecha.getTime())) {
fecha = formatDate(fecha, "yyyy-MM-dd");
}
var values = fecha.split("-");
var dia = values[2];
var mes = values[1];
var ano = values[0];
// cogemos los valores actuales
var fecha_hoy = new Date();
var ahora_ano = fecha_hoy.getYear();
var ahora_mes = fecha_hoy.getMonth() + 1;
var ahora_dia = fecha_hoy.getDate();
// realizamos el calculo
var edad = (ahora_ano + 1900) - ano;
if (ahora_mes < mes) {
edad--;
}
if ((mes == ahora_mes) && (ahora_dia < dia)) {
edad--;
}
if (edad > 1900) {
edad -= 1900;
}
// calculamos los meses
var meses = 0;
if (ahora_mes > mes && dia > ahora_dia)
meses = ahora_mes - mes - 1;
else if (ahora_mes > mes)
meses = ahora_mes - mes
if (ahora_mes < mes && dia < ahora_dia)
meses = 12 - (mes - ahora_mes);
else if (ahora_mes < mes)
meses = 12 - (mes - ahora_mes + 1);
if (ahora_mes == mes && dia > ahora_dia)
meses = 11;
// calculamos los dias
var dias = 0;
if (ahora_dia > dia)
dias = ahora_dia - dia;
if (ahora_dia < dia) {
ultimoDiaMes = new Date(ahora_ano, ahora_mes - 1, 0);
dias = ultimoDiaMes.getDate() - (dia - ahora_dia);
}
return edad + " años, " + meses + " meses y " + dias + " días";
}
function esNumero(strNumber) {
if (strNumber == null) return false;
if (strNumber == undefined) return false;
if (typeof strNumber === "number" && !isNaN(strNumber)) return true;
if (strNumber == "") return false;
if (strNumber === "") return false;
var psInt, psFloat;
psInt = parseInt(strNumber);
psFloat = parseFloat(strNumber);
return !isNaN(strNumber) && !isNaN(psFloat);
}
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
var now = DateTime.Now;
var age = DateTime.Now.Year - dob.Year;
if (now.Month < dob.Month || now.Month == dob.Month && now.Day < dob.Day) age--;
const getAge = birthDate => Math.floor((new Date() - new Date(birthDate).getTime()) / 3.15576e+10)
// today is 2018-06-13
getAge('1994-06-14') // 23
getAge('1994-06-13') // 24
getAge(birthday) {
const millis = Date.now() - Date.parse(birthday);
return new Date(millis).getFullYear() - 1970;
}
function dobvalidator(birthDateString){
strs = birthDateString.split("-");
var dd = strs[0];
var mm = strs[1];
var yy = strs[2];
var d = new Date();
var ds = d.getDate();
var ms = d.getMonth();
var ys = d.getFullYear();
var accepted_age = 18;
var days = ((accepted_age * 12) * 30) + (ms * 30) + ds;
var age = (((ys - yy) * 12) * 30) + ((12 - mm) * 30) + parseInt(30 - dd);
if((days - age) <= '0'){
console.log((days - age));
alert('You are at-least ' + accepted_age);
}else{
console.log((days - age));
alert('You are not at-least ' + accepted_age);
}
}
function calculate_age(date) {
var today = new Date();
var today_month = today.getMonth() + 1; //STRANGE NUMBERING //January is 0!
var age = today.getYear() - date.getYear();
if ((today_month > date.getMonth() || ((today_month == date.getMonth()) && (today.getDate() < date.getDate())))) {
age--;
}
return age;
};