English 中文(简体)
年龄计算
原标题:javascript - Age calculation
  • 时间:2010-11-02 09:25:24
  •  标签:
  • javascript

2 j 日期:

first is birthdate and second is a date to calculate age from that date.

这样做的最佳途径是什么。

最佳回答

这里是:

function getAge(d1, d2){
    d2 = d2 || new Date();
    var diff = d2.getTime() - d1.getTime();
    return Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
}
console.log( getAge(new Date(1978, 10, 3)) );

每月仔细研究。 Java印从
1978, 10, 3中计算。

问题回答
function calculateAge (birthDate, otherDate) {
    birthDate = new Date(birthDate);
    otherDate = new Date(otherDate);

    var years = (otherDate.getFullYear() - birthDate.getFullYear());

    if (otherDate.getMonth() < birthDate.getMonth() || 
        otherDate.getMonth() == birthDate.getMonth() && otherDate.getDate() < birthDate.getDate()) {
        years--;
    }

    return years;
}

例:

var age = calculateAge("02/24/1991", "02/24/2010"); // Format: MM/DD/YYYY
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();

  var dob = new Date(dateString.substring(6,10),
                     dateString.substring(0,2)-1,                   
                     dateString.substring(3,5)                  
                     );

  var yearDob = dob.getYear();
  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

<Date (MM/DD/YYYYYYYYY: 计算年龄

Age: 7 years, 1 month, and 15 days old.

将该日转至微秒,然后用gettime(),将数值推向后几年:

const MS_PER_YEAR = 1000 * 60 * 60 * 24 * 365.2425;
var years = Math.floor((dateNow.getTime() - dateThen.getTime()) / MS_PER_YEARS);

这里有一个例子,使用moment.js图书馆,现在很常见。 在许多其他答复中仅加上这一答案。

var banner = $("#banner-message")
var button = $("button")

// handle click and add class
button.on("click", function(){
  var inputValue = $("#txtInput").val();
  var age = parseInt(moment().diff(inputValue, years ,true));
  
$("#spantext").html(age +   years. );
  
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div id="banner-message">
  <p>Enter Date: <input type= text  id= txtInput  value= 1981-12-25  /></p>
  <label>Age is : </label><span id= spantext ></span> <br/>
  <p><button>Calculate Age</button></p>
</div>

最好的方式可能是将日期改为时间序列,如果日期是指示,则可能使用<代码>parse(<>>>>/code>。 然后用<代码>新日期(milliseconds)将新编号重新编号。

对1970年1月1日之前的日期来说,这也许不十分准确,但另外的排位数日、月等方法更合适。

var birth = new Date( 07/11/2003 );
var check = new Date();

var milliDay = 1000 * 60 * 60 * 24; // a day in milliseconds;


var ageInDays = (check - birth) / milliDay;

var ageInYears =  Math.floor(ageInDays / 365 );

http://www.jsfiddle.net/gaby/XDKa3/1/“rel=“nofollow”

如果你处于一个庞大的贾瓦特项目之中,你可能要[使用]一个框架。

Mootools More , 您有Date打 with a 。 这符合你们的需要。

它甚至provide localisation!

我修改了Mic的对策,以便今天成为使用者的出生日。 差异是,重新检查年龄的日期应定为当天午夜,而且(或)目前的日期应为23:59:59。 举例来说,看用户是否今天为18人,这将回去18人。

function getAge(d1){
    var now = new Date();
    var d2 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);
    var diff = d2.getTime() - d1.getTime();
    return Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
}
console.log(getAge(new Date(1992, 10, 17, 0, 0, 0)));

www.un.org/Depts/DGACM/index_spanish.htm 处理年限使用情况:

const getAgeFromBirthDate = (year, month, day) => {
   const date = new Date();
   date.setFullYear(date.getFullYear() - year);
   date.setMonth(date.getMonth() - month);
   //date.setDate(date.getDate() - day);
   return date;
};

console.log( getAgeFromBirthDate(1994, 07, 19).getFullYear() );

按本年度计算年龄

calculateExp(birthDate) {
    birthDate = new Date(birthDate);
    var now = new Date();
    otherDate = new Date(now.getFullYear(),now.getMonth(),now.getDate());
    var years = (otherDate.getFullYear() - birthDate.getFullYear() );


    if (otherDate.getMonth() < birthDate.getMonth() || otherDate.getMonth() == birthDate.getMonth() && otherDate.getDate() < birthDate.getDate()) {
        years--;
    }

    return years;
}
function getAge(dateOfBirth, tillDate) {
    var dob = new Date(dateOfBirth);
    var endDt = new Date(tillDate) || new Date();
    return new Date(endDt.getTime() - dob.getTime()).getUTCFullYear() - 1970;
}

Example: console.log(getAge( 1/1/2000 , 1/1/2016 )); // Format: MM/DD/YYYY





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签