Jscript 计算年龄

计算用户的年龄

 

下面的例子根据年来计算用户的年量。首先用当前的年和出生年相减,然后,如果今年的生日还没有过,就减1。我们的年龄定义不是基于严格定义的时间间隔,所以没有使用时间跨度计算。

 

var birthday = new Date("8/1/1985"); var today = new Date(); var years = today.getFullYear() - birthday.getFullYear(); // Reset birthday to the current year. birthday.setFullYear(today.getFullYear()); // If the user's birthday has not occurred yet this year, subtract 1. if (today < birthday) { years--; } alert("You are " + years + " years old.");

 

下面的例子是按月计算年龄。其中包括了怕段生日是否在这个月里出现的检查。

 

var birthday = new Date("8/1/1985"); var today = new Date(); var years = today.getFullYear() - birthday.getFullYear(); // Determine the number of months. var months = (years * 12) + (today.getMonth() - birthday.getMonth()); // Adjust the months if the birthday has not occurred yet in the current month. if (today.getDate() < birthday.getDate()) { months--; } alert("You are " + months + " months old.");

 

 

摘自MSDN - Date and Time Calculations (Windows Scripting - JScript)

http://msdn.microsoft.com/en-us/library/ee532932(VS.85).aspx

 

**这差不多是见过的计算年龄的最简单代码了。

你可能感兴趣的:(windows,Date,user,scripting)