最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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();
}
发布评论

评论列表(0)

  1. 暂无评论