Using Javascript, how do I make sure a date range is valid?

前端 未结 3 739
再見小時候
再見小時候 2020-12-01 23:46

In JavaScript, what is the best way to determine if a date provided falls within a valid range?

An example of this might be checking to see if the user input r

3条回答
  •  感动是毒
    2020-12-02 00:33

    var myDate = new Date(2008, 9, 16);
    
    // is myDate between Sept 1 and Sept 30?
    
    var startDate = new Date(2008, 9, 1);
    var endDate = new Date(2008, 9, 30);
    
    if (startDate < myDate && myDate < endDate) {
        alert('yes');
        // myDate is between startDate and endDate
    }
    

    There are a variety of formats you can pass to the Date() constructor to construct a date. You can also construct a new date with the current time:

    var now = new Date();
    

    and set various properties on it:

    now.setYear(...);
    now.setMonth(...);
    // etc
    

    See http://www.javascriptkit.com/jsref/date.shtml or Google for more details.

提交回复
热议问题