javascript - Check if date is current date or future date with datetime as input - Stack Overflow

I'm trying to check if the date entered in datetime field is a current or a future date. I've

I'm trying to check if the date entered in datetime field is a current or a future date. I've tried:

function validations(){
    var value=document.getElementById("showdate").value;
    if (new Date() > new Date(value)) {
        alert("Past date");
    }
}
<Form method="post" onsubmit="validations()" autoplete>
    <input type="datetime-local" name="showdate" class="right" required="required" id="showdate">
    <input type="submit">
</form>

I'm trying to check if the date entered in datetime field is a current or a future date. I've tried:

function validations(){
    var value=document.getElementById("showdate").value;
    if (new Date() > new Date(value)) {
        alert("Past date");
    }
}
<Form method="post" onsubmit="validations()" autoplete>
    <input type="datetime-local" name="showdate" class="right" required="required" id="showdate">
    <input type="submit">
</form>

But this code will work only with the date field.

Share Improve this question edited Aug 17, 2017 at 8:55 ssc-hrep3 16.1k8 gold badges51 silver badges96 bronze badges asked Aug 17, 2017 at 8:37 anchal sainianchal saini 1152 silver badges9 bronze badges 7
  • 4 what is value ... i.e. show how you call this function – Jaromanda X Commented Aug 17, 2017 at 8:39
  • 1 according to this fiddle, the code seems to work ... – fxlacroix Commented Aug 17, 2017 at 8:42
  • is value is date object or string? – Nemani Commented Aug 17, 2017 at 8:43
  • I edited the question. Value is from "datetime" input field. – anchal saini Commented Aug 17, 2017 at 8:50
  • Your example works in the current Chrome browser. – ssc-hrep3 Commented Aug 17, 2017 at 8:56
 |  Show 2 more ments

2 Answers 2

Reset to default 2

Generally, in JS, to pare dates you should try:

function isFutureDate(value) {
    d_now = new Date();
    d_inp = new Date(value)
    return d_now.getTime() <= d_inp.getTime();
}

Run regular parison operators on the getTime function of a Date object.

I believe, if you call the getTime() method of the date object, then it will return with the timestamp representation of the date object, so you will be able to pare the two datetimes better. Something like this:

function isFutureDate(value) {
    return new Date().getTime() <= new Date(value).getTime();
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745454724a4628432.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信