将日期字符串与特定日期范围进行比较

时间:2017-10-03 23:48:57

标签: javascript

HTML文件:



    function calculateAge() {
    
            var year = document.getElementsByName("year")[0].value,
                month = document.getElementsByName("month")[0].value,
                day = document.getElementsByName("day")[0].value;
    
            var dob = ("" + month + "/" + day + "/" + year);
     
                var today = new Date();
                var birthDate = new Date(dob);
                var age = today.getFullYear() - birthDate.getFullYear();
                var m = today.getMonth() - birthDate.getMonth();
                if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
                    age--;
                }
   
    
                //Validate if age is within rage
                if ((age >= 1) && (age <= 99)) {
    
                        //Determine Zodiac Sign
                        if (dob >= specificDateRange && dob <= specificDateRange  ) {
                            alert("Your age is: " + age + "\n");
                            alert("Your Zodiac Sign is Ox")
                        }
    
                } else {
                    alert("Age is out of range!");
                }
     }
&#13;
<select name="month" onchange="call()" >
             <option value="">select</option>
             <option value="1">Jan</option>
             <option value="2">Feb</option>
             <option value="3">Mar</option>
             <option value="4">Apr</option>
             <option value="5">May</option>
             <option value="6">Jun</option>
             <option value="7">Jul</option>
             <option value="8">Aug</option>
             <option value="9">Sep</option>
             <option value="10">Oct</option>
             <option value="11">Nov</option>
             <option value="12">Dec</option>
       </select>
    
            <select name="day">
               <option value="">select</option>
            </select>
    
            <select name="year" onchange="call()">
               <option>select</option>
            </select>
    
            <input type="submit" name="Search" value="Search" onclick="calculateAge()">
&#13;
&#13;
&#13;

我将monthdayyear存储在输出dob的var mm/dd/yy中。如何将其与特定范围进行比较,例如:dob <= 1/1/1990 && dob >= 1/1/2020?我应该将我的dob转换成日期吗?

对于ex:if (dob >= Feb.6,1913 && dob <= Jan.25,1914),它将输出我的中国十二生肖是牛

1 个答案:

答案 0 :(得分:0)

您可以从字符串new Date('2017-01-01')创建本机js日期对象并比较

new Date('2017-01-01') < new Date('2017-01-02') // true
new Date('2017-01-02') < new Date('2017-01-01') // false