moment.js isBetween()方法使用Aus日期格式

时间:2015-08-02 09:53:07

标签: javascript jquery date momentjs

我知道如何使用moment.js格式化我的日期,但是当我在isBetween()方法上阅读文档时,它会声明传递2个日期,格式为YYYY/MM/DD我的日期全部设置为DD/MM/YYYY如何使isBetween()方法识别澳大利亚日期格式。

http://momentjs.com/docs/#/query/is-between/

我的代码:

<script src="//code.jquery.com/jquery-1.11.3.js"></script>
<script src="js/moment-with-locales.js"></script>
<script src="js/moment-timezone-with-data.min.js"></script>

//checking to see if the user is 16 or 17 years old.
function parentGuardianRequired() {
    //todays date generated in a hidden field via php
    var signDate = $("#currentDate").val();
    //the users date of birth input
    var dateOfBirth = $("#dateOfBirth").val();

    //using moment to get the exact time of these dates while formatting the dates to AUS.
    var birthDate = moment(dateOfBirth, "DD/MM/YYYY");
    var currentDate = moment(signDate, "DD/MM/YYYY");

    //subtracting 16 and 18 years from todays date to always do a valid age check
    ageSixteen = currentDate.subtract(16, "years");
    ageSeventeen = currentDate.subtract(18, "years");

    //checks if the user is between the age of 16 and 17
    if (birthDate.isBetween(ageSixteen, ageSeventeen)) {
        //you are 16 or 17 years old
        console.log("TRUE");           
    } else {
        //You are not 16 or 17 years old
        console.log("FALSE");
    }   
}

1 个答案:

答案 0 :(得分:3)

moment.isBetween()适用于两个moment个对象。这里的问题是您在同一个对象上使用subtract两次,只有mutates it each time。它不会返回新对象。所以你的代码应该更像这样:

ageSixteen = moment(currentDate).subtract(16, "years");
ageSeventeen = moment(currentDate).subtract(18, "years");