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.
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))
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/
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>
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
Related
I've tried many ways to validate the date and time with Javascript functions but none seem to work. I'd like to alert users when their date input is of a past date whereas the time start cannot be the same as time end and it cannot be later than time end.
My HTML codes:
<p>
<label> Date:
<input type="date" id="date" name="date" required />
</label>
</p>
<p>
<label> Time start:
<input type="time" id="timeStart" name="timeStart" required />
</label>
</p>
<p>
<label> Time end:
<input type="time" id="timeEnd" name="timeEnd" required />
</label>
</p>
Javascript I tried:
function valiDate(date) {
var today=new Date();
var inputDate=document.getElementById("date").value;
if (inputDate < today) {
alert("Your event cannot happen in the past.");
}
}
function checkDate(date)
{
var dateInput=document.getElementById("date").value;
var parts=date.split("/");
var yearInput=parts[0];
var monthInput=parts[2];
var dayInput=parts[3];
var minYear = 1902;
var maxYear = (new Date()).getFullYear();
var maxMonth = (new Date()).getMonth();
var currentDay = (new Date()).getDate();
if (yearInput<maxYear || monthInput<maxMonth || dayInput<currentDay ) {
alert("Event cannot be held in the past. Move on.");
}
}
The method used for comparison of dates is wrong.
d1.getTime() === d2.getTime();
d1.getTime() !== d2.getTime();
Use getTime() operator or dates.compare() function.
If you want to split the dates, the use '-' to split them.
Here is a working jsFiddle:
https://jsfiddle.net/BoyWithSilverWings/rc08otjc/
Please try this
function validDate() {
var today=new Date();
var inputDate = new Date(document.getElementById("date").value);
today.setHours(0,0,0,0);
if (inputDate < today) {
alert("Your event cannot happen in the past.");
}
else {
var startTime = TimeinMillisec(document.getElementById("timeStart").value);
var endTime = TimeinMillisec(document.getElementById("timeEnd").value);
if( startTime > endTime)
alert("Event cannot be held");
else
alert("Done");
}
}
function TimeinMillisec(gTime)
{
var parts=gTime.split(" ");
var hhmm = parts[0].split(":");
hhmm[0] = parseInt(hhmm[0]);
if( parts[1].toLowerCase() === "pm")
hhmm[0] = parseInt(hhmm[0]+12);
var seconds = parseInt( ((+hhmm[0]) * 60 * 60) + ((+hhmm[1]) * 60));
return seconds;
}
I have written a javascript condition for checking the date condition.
What my requirement is, I have two textbox in which I add the dates, And what I want to check is that.
My both the dates which are entered into the textbox should not be greater than Current date.
I have tried the below code but it is accepting the date which is greater than system date.
var todayDate = new Date();
var todayMonth = todayDate.getMonth() + 1;
var todayDay = todayDate.getDate();
var todayYear = todayDate.getFullYear();
var todayDateText = todayMonth + "/" + todayDay + "/" + todayYear;
var Dt1 = document.getElementById('txtFormDt').value;
var Dt2 = document.getElementById('txtToDt').value;
if (todayDateText > Dt1)
{
alert("System Date Should be grater than From Date");
}
if (todayDateText > Dt2) {
alert("System Date Should be grater than To Date");
}
if (Dt2 < Dt1) {
alert("To Date Should be grater than From Date");
return false;
}
return true;
}
You can compare Date objects directly using the <, >, >= and <= operators but not == or === since Dates are also Objects. However, make sure you correctly parse the values from the inputs, e.g.
function checkDate(el) {
var form = el.form;
var now = new Date();
var date = parseMDY(form.startDate.value);
form.parsedDate.value = date;
if (!date || isNaN(+date)) {
form.result.value = "Invalid date";
} else {
form.result.value = date < now;
}
}
// Parse string in m/d/y format
// Returns invalid date if month or day out of range
function parseMDY(s) {
var b = s.split(/\D/);
var d = new Date(b[2], --b[0], b[1]);
return d && d.getMonth() == b[0]? d : new Date(NaN);
}
<form id="f0">
Insert date (m/d/y)<input type="text" name="startDate">
<input type="button" onclick="console.log(checkDate(this));" value="Check date">
<br>
Input date: <input name="parsedDate" readonly size="50">
<br>
Before today?<input name="result">
</form>
I have an input text that has a combination of date and time and display like this
04/01/2015 8:48PM
How can i convert this string to a date using the function new Date() in javascript? not output is shown
Here is what i've tried so far, i can only convert the date not the time.
HTML
<form name="frm1" >
<h3>Check in Date:</h3>
<input type="text" value="" class="datetimepicker_mask" name="dtp1" /><br><br>
<h3>Check out Date:</h3>
<input type="text" value="" class="datetimepicker_mask" name="dtp2" /><br><br>
<input type="button" onclick="computeDate()" value="Compute Difference" />
<br><b>No of days: </b>
<span id="date_difference"></span>
</form>
JAVSCRIPT
function computeDate() {
var dateTime1 = document.frm1.dtp1.value;
var dateTime2 = document.frm1.dtp2.value;
var startDate = new Date(dateTime1);
var endDate = new Date(dateTime2);
var timeDiff = Math.abs(endDate.getTime() - startDate.getTime());
if (timeDiff == 0) {
timeDiff = 1;
}
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
var total = parseFloat(diffDays) * parseFloat(roomRate);
document.getElementById("date_difference").innerHTML = diffDays;
document.getElementById("date_difference").style.visibility = "visible";
}
If the date format is always the same, create a convience function that converts the date to a Date object
function convert(date) {
var dateArr = date.split(/[\s\/\:]/);
if (dateArr[4].toLowerCase().indexOf('pm') != -1)
dateArr[3] = (+dateArr[3]) + 12;
dateArr[4] = dateArr[4].replace(/\D/g,'');
dateArr[0]--;
return new Date(dateArr[2], dateArr[0], dateArr[1], dateArr[3], dateArr[4]);
}
FIDDLE
Here is an answer that will both solve this and make development easier. This suggestion will require an extra library for addressing such issues as you are having here- time, but you'll likely find it beneficial when working with JavaScript dates in general. It already looks like you're writing manual date functions. Abstract them away with robust libraries for solving these same issues that have come up again and again. Using date.js, here is how easy this becomes
Date.parse('04/01/2015 8:48PM ')
JSFiddle Example
You can create the Date object after parsing the dateString
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
you can use the parseDate function as following
var testDate = "04/01/2015 8:48PM";
console.log(parseDate(testDate));
function parseDate(dateStr){
var dateTime = dateStr.split(/\/| |:|(?=[PA])/);
for(var i=0; i<5; i++){
dateTime[i] = parseInt(dateTime[i]);
}
if(dateTime[5] == "PM"){
dateTime[3] += 12;
}
return new Date(dateTime[2], dateTime[1], dateTime[0], dateTime[3], dateTime[4]);
}
Try it at JSFiddle
Can't seem to find the problem. Every time I run it I get NaN for ageDale, been looking at it for a while now, its probably simple but I appreciate the help!
<p>Enter names in the fields, then click "Submit" to submit the form:</p>
<form name="form">
<input type="text" id="birthDate">
Current Date
<input type="text" id="currentDate">
<a id="Submit_Button" onclick="test();" href="javascript:void(0);" title="Submit">Submit</a>
</form>
<script>
function test() {
var birthDate = document.getElementById("birthDate");
var currentDate = document.getElementById("currentDate");
var ageDate = (birthDate.value - currentDate.value);
if(ageDate.value < 1) {
(ageDale = ageDate.value * -1)
}
else {
(ageDale = ageDate.value * 1)
}
alert(ageDale)
}
</script>
Also, is it necessary for me to have that else statement? or is there another way to set up this so its not needed?
This
ageDate.value
should be
ageDate
only. It's a variable and already contains only the difference from
birthDate.value - currentDate.value
if(ageDate.value < 1) {
// ^ here
(ageDale = ageDate.value * -1)
} //^ here
else {
(ageDale = ageDate.value * 1)
// ^ and here
You only need to fetch the value when getting data from, for example, input fields.
Also (depending on how you input them) it might be a problem to calculate dates. For debugging purposes you should
console.log()
your variable values, that way you will find out quickly where the error is.
A good place for a console.log() in your code would be, for example after this block:
var birthDate = document.getElementById("birthDate");
var currentDate = document.getElementById("currentDate");
var ageDate = (birthDate.value - currentDate.value);
console.log(ageDate);
SIDENOTE:
You might want to take a look at moment.js, which will help you with date calculations. For example, you can get differences between dates with moment.js like this:
var a = moment([2014, 12, 05]);
var b = moment([2014, 12, 06]);
a.diff(b, 'days') // 1
Try this:
var btn = document.getElementById("Submit_Button");
btn.onclick = function test() {
var birthDate = parseInt(document.getElementById("birthDate").value);
var currentDate = parseInt(document.getElementById("currentDate").value);
var ageDate = (birthDate - currentDate);
if(ageDate < 1) {
(ageDate = ageDate * -1)
}
else {
(ageDate = ageDate * 1)
}
alert(ageDate)
}
As baao said, you have spelling errors. After correcting those, you want to consider what your input is going to be, and make sure you are checking that the input is valid.
For example, if I type "September 10th" for my birthday and "December 10th" for the current date, your function will try and subtract two strings which is not valid. If you're going to use a custom input field for the date, you need to be sure its in a consistent and parseable format.
I'd recommend asking for just their birthday in a specific format and parsing it from there, since we can use Javascript to get the current date easily. For example, mm-dd-yy. We may re-write it as:
function test() {
//lets get the date, in the format 'mm-dd-yy'. You'd want to do error checking at some point if you're serious about it
var dateInput = document.getElementById("birthDate").value;
//get each individal date type by splitting them at the -, giving ['dd', 'mm', 'yy']
var dateSplit = dateInput.split('-');
//create a Javascript date object with the date we got
var birthDate = new Date(dateSplit[2], dateSplit[0], dateSplit[1]);
//create another with the current date and time
var currentDate = new Date();
// find the difference in milliseconds
var dateDifference = Math.abs(birthDate.getTime() - currentDate.getTime());
// convert to years
var age = dateDifference / (1000 * 3600 * 24 * 365);
alert(age);
}
<p>Enter names in the fields, then click "Submit" to submit the form:</p>
<form name="form">
Birth Date (dd-mm-yy):
<br>
<input type="text" id="birthDate">
<br>
<a id="Submit_Button" onclick="test();" href="javascript:void(0);" title="Submit">Submit</a>
</form>
just modify this code
var birthDate = document.getElementById("birthDate");
var currentDate = document.getElementById("currentDate");
var ageDate = (birthDate.value - currentDate.value);
if(ageDate.value < 1) {
(ageDale = ageDate.value * -1)
}
else {
(ageDale = ageDate.value * 1)
}
with this
var vbirthdate = new Date(document.getElementById("birthDate").value);
var vcurrentdate = new Date(document.getElementById("currentDate").value);
var ageDate = Math.floor((vbirthdate-vcurrentdate)/(1000*60*60*24));
if(ageDate < 1) {
(ageDate = ageDate * -1)
} // no need to do something like this (ageDate *1) if it is already a positive number, just check if it's a negative then convert it to a positive number
you can try the code at http://jsfiddle.net/kapasaja/duco4cqa/5/
what you asking is similar to this post
All,
I'm using the jQuery UI for the date picker. I'm trying to check with javascript though that the date the user has entered is in the past. Here is my form code:
<input type="text" id="datepicker" name="event_date" class="datepicker">
Then how would I check this with Javascript to make sure it isn't a date in the past? Thanks
$('#datepicker').datepicker().change(evt => {
var selectedDate = $('#datepicker').datepicker('getDate');
var now = new Date();
now.setHours(0,0,0,0);
if (selectedDate < now) {
console.log("Selected date is in the past");
} else {
console.log("Selected date is NOT in the past");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<input type="text" id="datepicker" name="event_date" class="datepicker">
var datep = $('#datepicker').val();
if(Date.parse(datep)-Date.parse(new Date())<0)
{
// do something
}
To make the answer more re-usable for things other than just the datepicker change function you can create a prototype to handle this for you.
// safety check to see if the prototype name is already defined
Function.prototype.method = function (name, func) {
if (!this.prototype[name]) {
this.prototype[name] = func;
return this;
}
};
Date.method('inPast', function () {
return this < new Date($.now());// the $.now() requires jQuery
});
// including this prototype as using in example
Date.method('addDays', function (days) {
var date = new Date(this);
date.setDate(date.getDate() + (days));
return date;
});
If you dont like the safety check you can use the conventional way to define prototypes:
Date.prototype.inPast = function(){
return this < new Date($.now());// the $.now() requires jQuery
}
Example Usage
var dt = new Date($.now());
var yesterday = dt.addDays(-1);
var tomorrow = dt.addDays(1);
console.log('Yesterday: ' + yesterday.inPast());
console.log('Tomorrow: ' + tomorrow.inPast());
Simply convert the dates into milliseconds and subtract
let givenDate1 = new Date("10/21/2001") // Past Date
let givenDate2 = new Date("10/21/2050") // future Date
If diff is positive, then given date is PAST
let diff = new Date().getTime() - givenDate1.getTime();
if (diff > 0) {
console.log('Given Date givenDate1 is in Past');
}
If diff is negative, then given date is Future
let diff = new Date().getTime() - givenDate2.getTime();
if (diff < 0) {
console.log('Given Date givenDate2 is in Future');
}
You can use isPast(date) method from date-fns library.
import { isPast } from 'date-fns'
console.log(new Date('1991-06-17'));
// returns true.
console.log(new Date('2191-06-17'));
// returns false.
More info about the method:
https://date-fns.org/v2.29.3/docs/isPast
function isPrevDate() {
alert("startDate is " + Startdate);
if(Startdate.length != 0 && Startdate !='') {
var start_date = Startdate.split('-');
alert("Input date: "+ start_date);
start_date=start_date[1]+"/"+start_date[2]+"/"+start_date[0];
alert("start date arrray format " + start_date);
var a = new Date(start_date);
//alert("The date is a" +a);
var today = new Date();
var day = today.getDate();
var mon = today.getMonth()+1;
var year = today.getFullYear();
today = (mon+"/"+day+"/"+year);
//alert(today);
var today = new Date(today);
alert("Today: "+today.getTime());
alert("a : "+a.getTime());
if(today.getTime() > a.getTime() )
{
alert("Please select Start date in range");
return false;
} else {
return true;
}
}
}