ITeye博客

js获取离生日的天数,和年数

sohighthesky · 2010-06-10 12:44 · javascript(js) · Web前端 · Markdown

不计算小时: [code="js"]/* *reg生日 *tod当前日期,从服务器获取 *cd提前提醒的天数范围 */ function getBirthday(reg,tod,cd){ var d=new Date(reg),n=new Date(tod),y=n.getFullYear(), yd=new Date(y,n.getMonth(),n.getDate()), ds=(new Date(y,d.getMonth(),d.getDate())-yd)/(1000*60*60*24),//月日份相差天数 ys=n.getFullYear()-d.getFullYear();//相差年数 if(ds < -200){//修正类似1月1号提前5天的提醒, ds=(new Date(d.getFullYear()+(++ys),d.getMonth(),d.getDate())-yd)/(1000*60*60*24) } if(ds > cd)return null;//不在范围内返回null,不提醒 return [ys,ds] } document.write(getBirthday('1/1/2005','12/29/2008',5)); document.write("
"); document.write(getBirthday('12/29/2005','1/2/2008',5)); document.write("
"); document.write(getBirthday('3/4/2005','3/1/2008',5));[/code] 版本2:在指定日期绝对值范围内也返回 [code="js"]function getBirthday1(reg,tod,cd){ var d=new Date(reg),n=new Date(tod),y=n.getFullYear(), yd=new Date(y,n.getMonth(),n.getDate()), dd=1000*60*60*24, ds=(new Date(y,d.getMonth(),d.getDate())-yd)/dd,//月日份相差天数 ys=n.getFullYear()-d.getFullYear();//相差年数 if(ds < -200){//修正类似1月1号提醒5天的提醒, ds=(new Date(d.getFullYear()+(++ys),d.getMonth(),d.getDate())-yd)/dd } else if(ds>200){ ds=(new Date(d.getFullYear()+ys-1,d.getMonth(),d.getDate())-yd)/dd } if(Math.abs(ds) > cd)return null;//不在范围内返回null,不提醒 return [ys,ds] }[/code]

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。