最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Date Difference in Javascript - Stack Overflow

programmeradmin1浏览0评论

I am developing a system which requires that you should be at least 18 years old to register.

For doing this validation i have implemented date difference in javascript in following way, but it is not accurate, is there any javascript function or other way to do this?

var d1=new Date(1985,1,28);
var d2=new Date();
var milli=d2-d1;
var milliPerYear=1000*60*60*24*365.26;
var years_old=milli/milliPerYear; 

I am developing a system which requires that you should be at least 18 years old to register.

For doing this validation i have implemented date difference in javascript in following way, but it is not accurate, is there any javascript function or other way to do this?

var d1=new Date(1985,1,28);
var d2=new Date();
var milli=d2-d1;
var milliPerYear=1000*60*60*24*365.26;
var years_old=milli/milliPerYear; 
Share Improve this question asked Jan 28, 2012 at 11:00 mackmack 1,8285 gold badges22 silver badges30 bronze badges 2
  • 2 Any client side validation can easily be circumvented. Always validate on the server side. Although in this case, you cannot even ensure that a person provides his real birthday. – Felix Kling Commented Jan 28, 2012 at 11:03
  • Yeah - this is more of a user-consent liability issue, rather than a full credit check or anything. Client-side validation is fine. – cloudfeet Commented Nov 28, 2014 at 14:24
Add a ment  | 

2 Answers 2

Reset to default 8

Legally being at least 18 years old is not about the amount of time corresponding to the average duration of 18 years (years aren't always the same length). It is about the current date being after your 18th birth date. Hence, you should just add 18 to the year count on the birthdate and see if this is before or after the present date, e.g.

var birthDate = new Date(1985,1,28);
var today = new Date();
if (today >= new Date(birthDate.getFullYear() + 18, birthDate.getMonth(), birthDate.getDate())) {
  // Allow access
} else {
  // Deny access
}

You should do the same validation on the server side as well.

Note that this also handles people born on 29th February the correct way: in this case JavaScript will create a date object to represent the 1st March 18 years later.

I like http://momentjs./

<script src="moment.min.js"></script>
<script>
  var dob = new moment([1985,1,28]);
  var age = new.moment().diff(dob, 'years')

  if (age >= 18) { 
    ...
  }
</script>
发布评论

评论列表(0)

  1. 暂无评论