//根据日期(生日)获取真实年龄
function parseDate(str){
if(str.match(/^\d{4}[\-\/\s+]\d{1,2}[\-\/\s+]\d{1,2}$/)){
return new Date(str.replace(/[\-\/\s+]/i,'/'))
}else if(str.match(/^\d{8}$/)){
return new Date(str.substring(0,4)+'/'+str.substring(4,6)+'/'+str.substring(6))
}else{
alert('date parse error')
}
}
function getAge(){
var age;
var aDate=new Date();
var thisYear=aDate.getFullYear();
var thisMonth=aDate.getMonth()+1;
var thisDay=aDate.getDate();
var brith=parseDate(document.getElementById("date1").value);
brithy=brith.getFullYear();
brithm=brith.getMonth()+1;
brithd=brith.getDate();
if(thisYear-brithy<0) {
alert("输入错误!");
age="";
}else{
if(thisMonth-brithm<0){
age = thisYear-brithy-1;
}else{
if(thisDay-brithd>=0) {
//alert(thisDay+'-'+brithd+"_ddd");
age = thisYear-brithy;
}else{
age = thisYear-brithy-1;
}
}
}
document.getElementById("date2").value=age;
}
HTML代码
<from name="theform">
生日:<input name="date1" id="date1" onblur="getAge()">
年龄:<input name="date2" id="date2">
</form>
-----------------------------------------------华丽的分割线-------
//取生肖, 参数必须是四位的年
function getshengxiao(yyyy){
var arr=['猴','鸡','狗','猪','鼠','牛','虎','兔','龙','蛇','马','羊'];
return /^\d{4}$/.test(yyyy)?arr[yyyy%12]:null
}
// 根据生日的月份和日期,计算星座。
function getAstro(month,day){
var s="魔羯水瓶双鱼牡羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";
var arr=[20,19,21,21,21,22,23,23,23,23,22,22];
return s.substr(month*2-(day<arr[month-1]?2:0),2);
}
结合AngularJs模板使用例子:
<tr ng-repeat="fans in vm.data.users">
<td ng-bind="$index+1"></td>
<td ng-bind="fans.nickname">郑州网建</td>
<td ng-bind="fans.gender=='m'?'男':'女'"></td>
<td ng-bind="vm.getDate(fans.birthday)"></td>
<td ng-bind="vm.getAstro(fans.birthday)+'座'"></td>
<td ng-bind="vm.unix_to_datetime(1399259663*1000)"></td>
</tr>
PS:unix时间戳转换成日期时间:(关于上边时间戳1399259663为什么*1000,是因为根据不同的时区的问题,见下边的相关教程链接。)此转换后的结果是:2014/5/5 11:14:23
//Unix时间戳转换为时间格式
unix_to_datetime: function (datetime) {
if(window.VBArray){
datetime = datetime.replace(' +0800', '');
}
var now = new Date(datetime);
var year = now.getFullYear(),
month = now.getMonth()+1,
day = now.getDate(),
hour = now.getHours(),
minut = now.getMinutes(),
secon = now.getSeconds();
if(hour<10){
hour="0"+hour;
}
if(minut<10){
minut="0"+minut;
}
if(secon<10){
secon="0"+secon;
}
if(year != NaN){
return year+"/"+month+"/"+day+" "+hour+":"+minut+":"+secon;
}else{
return ""
}
}
相关教程: UTC和CST和GMT时间的区别