Bhargav Kukadiya
Bhargav Kukadiya

Reputation: 418

Php date difference through javascript

Can anyone tell me that how make the validation for the date input type in a form to count the difference between current date and the provided date to measure whether the difference is greater than 18 years or not.

Note: the JavaScript can be called on submit button and show result in alert box.

Upvotes: 0

Views: 242

Answers (4)

AGR
AGR

Reputation: 26

You could use something like this. But beware that this depends on the date string format of Javascript (Date constructor or Date.parse() : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date ). You should add an additional check to be sure you have a valid date string that the Date object will be able to parse.

<script>
function testDate() {
    var dateString = document.getElementById('datefield').value
    var currentDate = new Date();
    var providedDate = new Date(dateString);
    var diff = currentDate - providedDate;
    var years = diff/1000/60/60/24/365;
    if (years < 18) {
        alert('Not old enough !');
        return false
    }
}
</script>
<form onsubmit="return testDate()">
    <input type="date" id="datefield" />
    <input type="submit" />
</form>

Upvotes: 0

MarcoReni
MarcoReni

Reputation: 478

You can use valueAsDate to get the Date corresponding to the submitted value and confront that with "now" date.

HTML

<form id="myForm">
    <input type="date" name="dateInput" id="dateInput" value="2013-08-01" />
    <input type="submit">
</form>

JS

$(function() {
    $('#myForm').submit(function() {
        var _submittedDate = document.getElementById('dateInput').valueAsDate;
        var _now = new Date();
        var _milliPerYear =1000*60*60*24*365.26;
        var _dateDifference = (_now - _submittedDate);

        if ((_dateDifference/_milliPerYear) > 18) {
            alert("VALID");
        } else {
            alert("Invalid");
        }
        return false; //Avoid form submission for testing
    });

});

Here's a working example: http://jsfiddle.net/LinoLinux/rtvbysxs/1/

Upvotes: 0

mocak
mocak

Reputation: 405

You can simply subtract them to get difference in milliseconds.

var age = Math.floor((new Date() - new Date(dateString)) / (1000*60*60*24*365.25))

Upvotes: 2

jollyjoyce1995
jollyjoyce1995

Reputation: 321

you probably should add an event handler for the submit of the form, and check the date in that handler. How to calculate the age is described here:

function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
    age--;
}
return age;
}
console.log('age: ' + getAge("2010/08/10"));

jsfiddle

Upvotes: -1

Related Questions