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.
-
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
2 Answers
Reset to default 2Generally, 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();
}