日期的 JQuery 年龄计算

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5524743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:18:26  来源:igfitidea点击:

JQuery Age calculation on date

jquery

提问by seoppc

Am I missing something in the following jQuery code?

我在以下 jQuery 代码中遗漏了什么吗?

var dob = $('#date').val();
if(dob != ''){
    var today = new Date();
    var dayDiff = Math.ceil(today - dob) / (1000 * 60 * 60 * 24 * 365);
    var age = parseInt(dayDiff);
    $('#age').html(age+' years old');
}

I am getting the pre-fetched value of #date from MySQL db.

我从 MySQL db 中获取 #date 的预取值。

<input type="text" value="1988-04-07" id="#date" name="dob" /><p id="age"></p>

It's returning NaN, not the correct value.

它返回 NaN,而不是正确的值。

回答by Matt Ball

$('#date').val()returns the string '1988-04-07'. You need to parse it into an actual number.

$('#date').val()返回字符串'1988-04-07'。您需要将其解析为实际数字。

dob = new Date(dob);
var today = new Date();
var age = Math.floor((today-dob) / (365.25 * 24 * 60 * 60 * 1000));
$('#age').html(age+' years old');

As @esqew points out, you also need to change id="#date"to id="date".

正如@esqew 指出的,您还需要更改id="#date"id="date".

回答by Dinesh Rabara

function getAge(dateString) {
  var now = new Date();
  var today = new Date(now.getYear(),now.getMonth(),now.getDate());

  var yearNow = now.getYear();
  var monthNow = now.getMonth();
  var dateNow = now.getDate();
 //date must be mm/dd/yyyy
  var dob = new Date(dateString.substring(6,10),
                     dateString.substring(0,2)-1,                   
                     dateString.substring(3,5)                  
                     );

  var yearDob = dob.getFullYear();
  var monthDob = dob.getMonth();
  var dateDob = dob.getDate();
  var age = {};
  var ageString = "";
  var yearString = "";
  var monthString = "";
  var dayString = "";


  yearAge = yearNow - yearDob;

  if (monthNow >= monthDob)
    var monthAge = monthNow - monthDob;
  else {
    yearAge--;
    var monthAge = 12 + monthNow -monthDob;
  }

  if (dateNow >= dateDob)
    var dateAge = dateNow - dateDob;
  else {
    monthAge--;
    var dateAge = 31 + dateNow - dateDob;

    if (monthAge < 0) {
      monthAge = 11;
      yearAge--;
    }
  }

  age = {
      years: yearAge,
      months: monthAge,
      days: dateAge
      };

  if ( age.years > 1 ) yearString = " years";
  else yearString = " year";
  if ( age.months> 1 ) monthString = " months";
  else monthString = " month";
  if ( age.days > 1 ) dayString = " days";
  else dayString = " day";


  if ( (age.years > 0) && (age.months > 0) && (age.days > 0) )
    ageString = age.years + yearString + ", " + age.months + monthString + ", and " + age.days + dayString + " old.";
  else if ( (age.years == 0) && (age.months == 0) && (age.days > 0) )
    ageString = "Only " + age.days + dayString + " old!";
  else if ( (age.years > 0) && (age.months == 0) && (age.days == 0) )
    ageString = age.years + yearString + " old. Happy Birthday!!";
  else if ( (age.years > 0) && (age.months > 0) && (age.days == 0) )
    ageString = age.years + yearString + " and " + age.months + monthString + " old.";
  else if ( (age.years == 0) && (age.months > 0) && (age.days > 0) )
    ageString = age.months + monthString + " and " + age.days + dayString + " old.";
  else if ( (age.years > 0) && (age.months == 0) && (age.days > 0) )
    ageString = age.years + yearString + " and " + age.days + dayString + " old.";
  else if ( (age.years == 0) && (age.months > 0) && (age.days == 0) )
    ageString = age.months + monthString + " old.";
  else ageString = "Oops! Could not calculate age!";

  return ageString;
}

// A bit of jQuery to call the getAge() function and update the page...
$(document).ready(function() {
  $("#submitDate").click(function(e) {
    e.preventDefault();

    $("#age").html(getAge($("input#date").val()));

  });
});

and HTML IS

回答by Amritpal Singh

Firstly the id mentioned in the textbox should not contain '#'

首先,文本框中提到的 id 不应包含“#”

I have also Created a fiddle

我还创建了一个小提琴

Oops i had't checked the date it was posted on

哎呀,我没有检查它发布的日期

回答by Superve

$("#dob").change(function(){

    var today = new Date();
    var birthDate = new Date($('#dob').val());
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
   return $('#age').html(age+' years old');
});

It worked for me

它对我有用

回答by Parveen Chauhan

 jQuery("#dob").on('change',function(){
       var dob1 = jQuery(this).val();
       var dob = $.datepicker.formatDate('yy-mm-dd', new Date(dob1));
       var str = dob.split('-');    
       var firstdate=new Date(str[0],str[1],str[2]);
       var today = new Date();        
       var dayDiff = Math.ceil(today.getTime() - firstdate.getTime()) / (1000 * 60 * 60 * 24 * 365);
       var age = parseInt(dayDiff);
       jQuery("#age").html(age+' years old');
   });




<input type="text" id="#dob" class="datepicker" name="dob" /><p id="age"></p>

回答by Adam888

That's what worked for me while all the rest gave NaN:

这就是对我有用的,而其余的都给了 NaN:

That only works if the dob format is mm/dd/yy

仅当 dob 格式为mm/dd/yy时才有效

function getAge(dob) { return ~~((new Date()-new Date(dob))/(31556952000)) }
$("#dob").val()
$(dob).change(function(){
  $('.age').val(getAge($(this).val()));
});

Please see my jsfiddle http://jsfiddle.net/A888/98c21nbz/1/

请看我的 jsfiddle http://jsfiddle.net/A888/98c21nbz/1/

回答by srPolash

We can calculate age by using moment.min.js. In HTML file, Please add below line

我们可以通过使用 moment.min.js 来计算年龄。在 HTML 文件中,请添加以下行

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>

Js Code:

JS代码:

var dob = $('#date').val();
if(dob != ''){
    var age = moment().diff(moment(dob, 'YYYY-MM-DD'), 'years');
    $('#age').html(age+' years old');
}

Hope this will help you.

希望这会帮助你。