5

現在の日付とユーザーが入力した日付の年の差を取得するjavascript関数を教えてください。

私はこれを試しましたが、うるう年を数えることはできません

var yearOld=2000
var dateOld=11
var mnthOld=1;
var currendDate=new Date(); // 9 - jan - 2013

var oldDate=new Date(yearOld,mnthOld-1,dateOld);

var timeDiff =currendDate-oldDate ;

var diffDays = timeDiff / (1000 * 3600 * 24 * 365); 

結果は来ている 13.00789 何か 13 未満になるはずです

どんな助けでも大歓迎です

4

5 に答える 5

12
function getAge(birthDateString) {
    var today = new Date();
    var birthDate = new Date(birthDateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}

if(getAge("27/06/1989") >= 18) {
    alert("You have 18 or more years old!");
} 
于 2013-01-09T08:55:22.947 に答える
5

日付関連の操作が多い場合は、MomentJS http://momentjs.com/の使用を検討してください。最初の 2 つの例を確認してください。質問に合っていると思います。

于 2013-01-09T08:54:52.373 に答える
0

http://www.datejs.com/は、日付を使用したあらゆる種類の計算に役立つライブラリです。

于 2013-01-09T08:56:00.087 に答える
0
// 1. Get current date
// 2. Add 13 to the year in DOB.
// 3. check if current year is less than dob-year. If not person is older than 13 years
// 4. And so on check for month and date

var date_of_birth = '2015-12-26' // example DOB
var is_13 = true; // flag for 13 

dob = date_of_birth.trim(); // trim spaces form DOB
y = parseInt(dob.substr(0,4)); // fetch year using substr() from DOB
m = parseInt(dob.substr(5,2)); // fetch month using substr() from DOB
d = parseInt(dob.substr(8,2)); // fetch date using substr() from DOB
// the above logic can change depending on the format of the input DOB

var r = new Date(); // Gets current Date

if(r.getFullYear() <= (parseInt(y) + 13)){ 
       if((r.getMonth()+1) <= m){
            if(r.getDate() < d){
                is_13 = false;
                console.log('less than 13');
}}}
于 2018-12-27T13:11:24.860 に答える