Validating time and date in javascript for html form - javascript

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;
}

Related

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.
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

How to check whether the date is in past or not?and How to get difference between two dates? by input tag type date and type time

Restaurant app booking a table feature.
Date input by <input type="date"> and <input type="time">
What I need.
1.How check whether the given/input date and time is in past or not.If past not valid,if future valid for booking.
2.How to get difference between two dates and times.So that I can show time left for booked table,and the user is allowed to get a table within the booked date and time mentioned.(may be by setInterval())
HTML
<html>
<head>
</head>
<body>
<table id="tdatetime">
<tr><td>Select Date</td><td>Select Time</td></tr>
<tr><td><input type="date" id="bdate"></td><td><input type="time" id="btime"></td></tr>
</table>
<input type="button" id="bdtbtn" onclick="getbdtRL(this)" value="Book Now"></input>
</body>
</html>
JS
function getbdtRL(bookbtn)
{
var bdate=$("#bdate").val();
var btime=$("#btime").val();
var now = new Date();
var selectedDate=new Date(bdate);
var selectedTime=new Date(btime);
alert(btime);//returns for example- 2:00
alert(selectedTime);//returns Invalid Date
alert(selectedTime.toString());//returns Invalid Date
alert(selectedTime.toTimeString());//returns Invalid Date
alert(selectedTime.toDateString());//returns Invalid Date
//Date check is working
if(selectedDate<now)
{
alert("Selected Date is in Past");
}
else if(selectedDate>now)
{
alert("Selected Date is in Future");
}
else if(selectedDate==now)
{
alert("Selected Date is in Present");
}
//Time Check is not working by selectedTime
if(selectedTime<now)
{
alert("Selected Time is in Past");
}
else if(selectedTime>now)
{
alert("Selected Time is in Future");
}
else if(selectedTime==now)
{
alert("Selected Time is in Present");
}
//Time Check is not working by btime
if(btime<now)
{
alert("Selected Time is in Past");
}
else if(btime>now)
{
alert("Selected Time is in Future");
}
else if(btime==now)
{
alert("Selected Time is in Present");
}
}
//Date and Time Difference not working
var date=new Date();
var tempdate="2015-05-01";
var d1 = date;//tempdate;//
//alert("current date d1="+d1);
var d2 = RLArrBookDateSender;//receiving from db2 database data type is time which is already booked
//alert("booked date d2="+d2);
var DateDiff = {
inDays: function(d1,d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/(24*3600*1000));
}
};
alert("diff="+DateDiff.inDays(d1,d2));//no alert executes
You need to get the value from the DOM element, new Date only accepts a String or a Number or a series of Numbers, not DOM elements. Try entering a value in your Date and Time fields and entering the below code into the console.
alert( new Date( bdate.value + ' ' + btime.value ) - new Date > 0? 'future' : 'past');
I apologize if you were looking for more to the answer...but if the following is right then it should make sense...
(It's late, but i believe the logic is right...)
To compare dates:
var now = new Date();
var selectDate = new Date(bdate);
var diff = now.getTime() - selectDate.getTime();
if(diff > 0 || diff == 0) {
// selected date is in the past or is our current time
// (which should be tough to match down to milliseconds)
}
else if (diff < 0) {
// selected date has not past
}
To get the time left until a future date:
var now = new Date();
var validFutureDate = new Date(bdate);
var diff = validFutureDate.getTime() - now.getTime(); // in milliseconds
var dayDiff = parseInt(diff/(1000*60*60*24));
You can check it that way: http://jsfiddle.net/IonDen/gt4tqca9/
var date_in_future = new Date("2015-10-20"),
date_in_past = new Date("2014-05-15");
function check (date) {
var now = new Date().getTime(),
target = date.getTime();
if (target <= now) {
return false;
} else {
return true;
}
}
function diff (date) {
var now = new Date().getTime(),
target = date.getTime();
return now - target;
}
console.log(date_in_future);
console.log(date_in_past);
console.log("future date? " + check(date_in_future));
console.log("future date? " + check(date_in_past));
console.log("diff: " + diff(date_in_future));
console.log("diff: " + diff(date_in_past));

Calculate all dates in between given start and end date using javascript

I have a start-date and end-date and I want to calculate array of dates between these days based on a given duration.
for example,
if start date is 01/01/2015 and end date is 01/06/2015 and if I give duration as 3 months then out put should be:
01/04/2015
01/06/2015
How to achieve this using JavaScript and I need to display it in a form.
If you want to calculate difference between two dates using javascript:
Then,
function dateDiff() {
var dtFrom = document.getElementById('txtFromDate').value;
var dtTo = document.getElementById('txtToDate').value;
var dt1 = new Date(dtFrom);
var dt2 = new Date(dtTo);
var diff = dt2.getTime() - dt1.getTime();
var days = diff/(1000 * 60 * 60 * 24);
alert(dt1 + ", " + dt2);
alert(days);
return false;
}
function isNumeric(val) {
var ret = parseInt(val);
}
HTML:
<label for="txtFromDate">From Date : </label>
<input type="text" id="txtFromDate" name="txtFromDate" size="10" maxlength="10" value="03/25/2013"/><br/>
<label for="txtToDate">To Date : </label>
<input type="text" id="txtToDate" name="txtDate" size="10" maxlength="10" value="03/26/2013"/><br/>
<button id="btnCheck" name="btnCheck" onClick="dateDiff();" type="button">Difference</button>
AFTER EDIT:
Following solution is to get all dates between specified dates.
Working Demo
// using Datepicker value example code
$('#getBetween').on('click', function () {
var start = $("#from").datepicker("getDate"),
end = $("#to").datepicker("getDate");
var between = getDates(start, end);
$('#results').html(between.join('<br> '));
});
// This function doing this work.
function getDates(start, end) {
var datesArray = [];
var startDate = new Date(start);
while (startDate <= end) {
datesArray.push(new Date(startDate));
startDate.setDate(startDate.getDate() + 1);
}
return datesArray;
}

Convert a String to a Single Date in Javascript

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

Check if date is in the past Javascript

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;
}
}
}

Categories

Resources