jQuery function to compare date with current date

前端 未结 5 1904
生来不讨喜
生来不讨喜 2020-12-06 22:47

i am entering date of birth in form by entering date in separate text box ,selecting year from drop down and entering year in text box. Now i want to check that entered date

5条回答
  •  鱼传尺愫
    2020-12-06 23:12

    Comparing Date objects is trivial, just use the standard relational operators. When passed an Object they implicitly call the object's .valueOf() function which will return the time in milliseconds, suitable for comparison.

    The hard part is constructing a valid Date object in the first place.

    For reliability I strongly recommend using this version of the Date constructor rather than passing a string:

    new Date(year, month, day [, hour, minute, second, millisecond]);
    

    which ensures that the local date format doesn't matter. Passing a string can generate different results depending on whether the default date format is mm/dd/yyyy or dd/mm/yyyy in the user's locale.

    Don't forget that the year must be a full digit year, and that in this version January is represented by 0, not 1:

    var SelectedDate = new Date(
        $('[id$=txtYear]').val(),
        $('[id$=drpMonth]').val() - 1,
        $('[id$=spDate]').val());
    
    if (CurrentDate > SelectedDate) { ... }
    

提交回复
热议问题