Javascript 计算年龄并将其转化为变量

Javascript 计算年龄并将其转化为变量,javascript,validation,date-of-birth,Javascript,Validation,Date Of Birth,我查阅了很多方法来计算从出生日期算起的年龄,结果都是使用了return,而我是一个完全的新手,在编程的第一年,我正在做我的学校项目,我与所有这些争论和东西斗争 有人能告诉我,根据我的代码,我该如何将最终确定的计算过程作为数值变量插入 注意:这是代码的一小部分,所有对象都已正确定义。出生日期语法为DD/MM/YYYY。您需要一个返回正确值的函数。e、 g: <script type="text/javascript"> var BDyear = document.

我查阅了很多方法来计算从出生日期算起的年龄,结果都是使用了return,而我是一个完全的新手,在编程的第一年,我正在做我的学校项目,我与所有这些争论和东西斗争

有人能告诉我,根据我的代码,我该如何将最终确定的计算过程作为数值变量插入


注意:这是代码的一小部分,所有对象都已正确定义。出生日期语法为DD/MM/YYYY。

您需要一个返回正确值的函数。e、 g:

<script type="text/javascript"> 

         var BDyear = document.getElementById("BDyear").value
         var BDmonth = document.getElementById("BDmonth").value
         var BDday = document.getElementById("BDday").value
         var BDstate = false
         var BDcheck = true
         var Cdate = new Date()
         var Cyear = Cdate.getFullYear()

// sectioning age calulation into months with 28 30 and 31 days
if ((BDyear <= Cyear && BDyear >= 1920) && (BDmonth <= 12 && BDmonth >= 1) && (BDday <= 28 && BDday >= 1) && BDmonth == 2) {
                 document.getElementById("bderror").style.display = "none"
                 //
                 // Age calculation place holder
                 //
                 if (age < 13) {
                     document.getElementById("bderroryoung").display = 'inline'
                     BDstate = false
                 }
                 else {
                     document.getElementById("bderroryoung").display = 'none'
                     BDstate = true
                 }


             }

             if ((BDyear <= Cyear && BDyear >= 1920) && (BDmonth <= 12 && BDmonth >= 1) && (BDday <= 31 && BDday >= 1) && (BDmonth == 1 || BDmonth == 3 || BDmonth == 5 || BDmonth == 7 || BDmonth == 8 || BDmonth == 10 || BDmonth == 12)) {
                 document.getElementById("bderror").style.display = "none"
                 //
                 // Age calculation place holder
                 //
                 if (age < 13) {
                     document.getElementById("bderroryoung").display = 'inline'
                     BDstate = false
                 }
                 else {
                     document.getElementById("bderroryoung").display = 'none'
                     BDstate = true
                 }
             }


             if ((BDyear <= Cyear && BDyear >= 1920) && (BDmonth <= 12 && BDmonth >= 1) && (BDday <= 30 && BDday >= 1) && (BDmonth == 2 || BDmonth == 4 || BDmonth == 6 || BDmonth == 9 || BDmonth == 11)) {
                 document.getElementById("bderror").style.display = "none"
                 //
                 // Age calculation place holder
                 //
                 if (age < 13) {
                     document.getElementById("bderroryoung").display = 'inline'
                     BDstate = false
                 }
                 else {
                     document.getElementById("bderroryoung").display = 'none'
                     BDstate = true
                 }

             }
         }
 </script>

 <input class="text" id="BDyear" maxlength="4" style="width:8%" />&nbsp/&nbsp<input class="text" id="BDmonth" maxlength="2" style="width:5%" />&nbsp/&nbsp<input class="text" id="BDday" maxlength="2" style="width:5%" /><br />
                     <p id="bderror" style="position:absolute; top:70%; color:red; font:65% arial; display:none"> תאריך לידה לא תקין</p>
                     <p id="bderroryoung" style="position:absolute; top:70%; color:red; font:65% arial; display:none"> חובה להיות מעל גיל 13</p>
然后您需要调用该函数,并将其返回的值放入变量中,然后使用该变量

function returnAge(day, month, year) {
    var theAge;

    // ... do calculations and set theAge

    return theAge;
}

我建议使用date.js这样的日期库。您正在进行大量手动日期计算,这与date.js无关

您可以这样使用它:

var age = returnAge(BDday, BDmonth, BDyear)
if (age < 13) { /* do something */ }
else { /* do something */ }

您看到许多使用返回的示例的原因与将代码结构化为函数的优点是一致的。这将是你学习编程的下一步。函数将允许您创建可重用且更易于阅读和调试的代码块

回答你的问题:

var BDyear = document.getElementById("BDyear").value;
var BDmonth = document.getElementById("BDmonth").value;
var BDday = document.getElementById("BDday").value;

var birthDate = new Date(BDday + '/' + BDmonth + '/' +  BDyear);

if (birthDate != null) {
    var age = calculateAge(birthDate);
}


function calculateAge(birthday) {
    var ageDifMs = Date.now() - birthday.getTime();
    var ageDate = new Date(ageDifMs); 
    return Math.abs(ageDate.getUTCFullYear() - 1970);
}
更新

上面没有考虑闰年[即使我们将一年中的天数改为365.242199]。感觉好多了,因为我们正在做一些有趣的数学,但如果我们只是这样比较月份和日期,我们可能会忘记特殊情况:

var BDyear = document.getElementById("BDyear").value
var BDmonth = document.getElementById("BDmonth").value
var BDday = document.getElementById("BDday").value

// create a new date object based on your input
var BDdate  = new Date(BDyear, BDmonth, BDday);

// get today's date
var Today = new Date();

// getTime returns time in milliseconds
var DateDiff = Today.getTime() -BDdate.getTime();

// convert milliseconds to years and return the floor

// milliseconds in a year
var YearMilliseconds = 1000 * 60 * 60 * 24 * 365;

// here is your variable with the age
var Age = Math.floor(DateDiff / YearMilliseconds);

好的,假设我将它返回到一些html输入或其他东西中,使其不可见,然后在下一行中,我将获取输入的值,它是从出生日期提取的实际年龄吗?或者,是否可以在不使用所有processI假设的情况下在id为bddaysanswer的输入元素中显示答案。如果你做了这样一个输入元素,答案会和我共享的代码一起出现在那里。我实际上想用它来限制13岁以下的用户注册。在我达到这个年龄后,我想看看它是否低于13岁,然后用一个错误取消注册过程啊。。。我想我现在明白了。我仍然需要学习如何使用return,但是这让事情变得更清楚了。非常感谢。你能把它分解并解释每一行的作用吗?除了我提到的明显的问题,我是一个完全的新手,我正在努力理解我在做什么,这真的很好。有这么多的方法来做这样的事情,但我认为这一个实际上会适合我的功能,而不需要任何其他功能和更多的斗争。这也意味着我可以在一定的天数内删除该分区数月,对吗?我很可能会在明天早上看到你的评论,但我肯定会尝试你的答案-它看起来简单易懂,并插入到我的代码中。一千次谢谢你,先生!你帮了我很多忙!谢谢我想给你一些适合你现有代码和编程水平的东西。我真的很想鼓励你在适当的时候学习函数等等。Javascript和编程都是非常棒的东西,你应该以自己熟悉的速度前进,并在现有知识的基础上继续前进。你可以放弃分段数月或数天,但我忽略了一件事,那就是考虑闰年。稍后会有更多内容……我发布的代码中没有显示实际的函数。所以我确实使用函数,但我想知道的是,你是否能从同一个函数的不同部分得到不同的回报。否则,我将不得不为不同函数的每个输入中断每个验证部分,并让它们同时调用所有函数
var BDdate  = new Date(BDyear, BDmonth, BDday);

// get today's date
var Today = new Date();

// get current month.  adjust by one so it is using same scale as user input [getMonth() returns 0-11);
var TodayMonth = Today.getMonth() + 1;

// difference in years
var Age = Today.getFullYear() -BDdate.getFullYear();

// adjust for month/day
// if the birth month was greater than today, subtract a year
// if the birth month is the same as this one, we need to compare the actual day
if (BDmonth > TodayMonth || (BDmonth === TodayMonth && BDday > Today.getDate())) {
    // oops, it's not our birthday yet, so subtract a year
    Age = Age - 1;    
}

// Age is ready to use