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

javascript - Check if form date is older than 4 months - Stack Overflow

programmeradmin2浏览0评论

I have a form with a date picker, which checks if the selected date is not older than 4 months. But my script doesn't work now, because of a new year (2018).

if ((today.getMonth() + 11) - (date.getMonth() + 11) > 4) {
    console.log("test");
}

It doesn't check for the months of 2017. I can't find a solution to fix this, does anyone know how to fix this?

I have a form with a date picker, which checks if the selected date is not older than 4 months. But my script doesn't work now, because of a new year (2018).

if ((today.getMonth() + 11) - (date.getMonth() + 11) > 4) {
    console.log("test");
}

It doesn't check for the months of 2017. I can't find a solution to fix this, does anyone know how to fix this?

Share Improve this question edited Jan 2, 2018 at 11:10 can asked Jan 2, 2018 at 10:10 cancan 2142 silver badges15 bronze badges 1
  • your if conditions are kind of redundant – orangespark Commented Jan 2, 2018 at 10:15
Add a ment  | 

2 Answers 2

Reset to default 6
 if(today - date > 1000/*ms*/ * 60/*s*/ * 60/*min*/ * 24/*h*/ * 30/*days*/ * 3/*months*/)
   alert("to old!");

Alternatively:

 const fourMonthsAgo = new Date();
 fourMonthsAgo.setMonth(fourMonthsAgo.getMonth() - 4);

 if(+fourMonthsAgo > +date)
  alert("to old");

Just pare like this;

  var diff =(today.getTime() - date.getTime()) / 1000;
  diff = diff / (60 * 60 * 24 * 10 * 3);
  var diffMonths = Math.abs(Math.round(diff));
  if(diffMonths > 4)
  {
    var $errordate = $( "<div id='error-field' class='error-field'><p>Error text</p></div>" );
    $("#divContainer").append($errordate);
    $('#nextButton').prop('disabled', true);
  }

Demo

发布评论

评论列表(0)

  1. 暂无评论