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?

2
  • @Bhushan Kawadkar: this not duplicate question. Please care fully read my question Commented Jun 20, 2017 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. Commented Jun 20, 2017 at 11:45

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

4 Comments

i am getting with time also. here millisecondsDiff getting NaN
@Durga When is it getting NaN? It may do that if the dates have not been selected.
but fromDate and toDates getting dates
i am getting date with time also

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.