0

I am new to jquery, i am getting from date and to date with date picker.

Here i am trying to add validation, i want from date and to date between have 30 days only.

var fromDate = $("#from_txn_date").val();//2017-02-20 00:00:00
var toDate = $("#to_txn_date").val();//2017-06-20 00:00:00

above date have 4 months difference(approximately 120 days),but i want fromDate not greater than to 30 days.

if(fromDate > 30)
{
alert("**if**");
return false;
}else{
alert("**else**");
}

i tried my way but it's not working.

What's wrong in my code?

Durga
  • 545
  • 7
  • 21
  • 39
  • @Bhushan Kawadkar: this not duplicate question. Please care fully read my question – Durga Jun 20 '17 at 11:35
  • if i am not mistaken your problem is with date comparison. Here you are comparing date text instead of date object which results into wrong output. The link i referred to your question does the same thing of date conversion and comparision. Below answer posted by Okx is doing same thing. Let me know if any concerns. – Bhushan Kawadkar Jun 20 '17 at 11:45

1 Answers1

1

Try this:

function submit() {
  var fromDate = new Date(document.getElementById("from").value);
  var toDate = new Date(document.getElementById("to").value);
  var millisecondsDiff = toDate - fromDate;
  if(millisecondsDiff > 2592000000) { // 30 days
    document.getElementById("output").innerHTML = "Range too big!";
  } else {
    document.getElementById("output").innerHTML = "Range is okay.";
  }
}
<input id="from" type="date">
<input id="to" type="date">
<br/>
<button onclick="submit()">
  Submit
</button>
<div id="output">

</div>
Okx
  • 353
  • 3
  • 23