Two textbox dates should not be greater to current date in javascript - javascript

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>

Related

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

JSP Date validation

I have an jsp page where the user selects two dates. I need to validate this date to ensure that the 1st date is not less than today's date. This is the script I am using:
var todaysDate = new Date();
if(document.frm.rentedOnDate.value < todaysDate )
{
alert("Rented date should not be before today");
document.frm.bank.focus();
return false;
}
if(document.frm.rentedOnDate.value> document.frm.returnDate.value )
{
alert("Return date should be after rented date");
document.frm.bank.focus();
return false;
}
These are the date selection fields:
<p>Select Rental Date: <input type="date" name="rentedOnDate"> </p>
<p>Select Return Date: <input type="date" name="returnDate"> </p>
The second script function works when the user enters a return date which is before the rented date but the first function does not work. Any ideas why?
Your second test is comparing strings, so I wouldn't count on it being perfectly reliable (a preceding zero could break it for instance).
You need to convert the strings (the .value fields) to proper date objects, and then compare them. This will resolve your first check, and improve your second check.
This function will parse a date provided in the "yyyy-mm-dd" fashion (optional 2-digit year yields 20xx). null is returned for an invalid date.
function getDate(str)
{
var dateParts = /^(\d\d(?:\d\d)?)-(\d\d?)-(\d\d?)$/.exec(str);
if (dateParts === null)
{
return null;
}
var year = parseInt(dateParts[1]);
if (year < 100)
{
year += 2000;
}
var month = parseInt(dateParts[2]) - 1;
var day = parseInt(dateParts[3]);
var result = new Date(year, month, day);
return year === result.getFullYear()
&& month === result.getMonth()
&& day === result.getDate() ? result : null;
}
function validateDate(dates){
re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var days=new Array(31,28,31,30,31,30,31,31,30,31,30,31);
if(regs = dates.match(re)) {
// day value between 1 and 31
if(regs[1] < 1 || regs[1] > 31) {
return false;
}
// month value between 1 and 12
if(regs[2] < 1 || regs[2] > 12) {
return false;
}
var maxday=days[regs[2]-1];
if(regs[2]==2){
if(regs[3]%4==0){
maxday=maxday+1;
}
}
if(regs[1]>maxday){
return false;
}
return true;
} else {
return false;
}
}

Check if one date is between two dates

I need to check if a date - a string in dd/mm/yyyy format -
falls between two other dates having the same format dd/mm/yyyy
I tried this, but it doesn't work:
var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "02/07/2013";
var from = Date.parse(dateFrom);
var to = Date.parse(dateTo);
var check = Date.parse(dateCheck );
if((check <= to && check >= from))
alert("date contained");
I used debugger and checked, the to and from variables have isNaN value.
Could you help me?
Date.parse supports the format mm/dd/yyyy not dd/mm/yyyy. For the latter, either use a library like moment.js or do something as shown below
var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "02/07/2013";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");
var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); // -1 because months are from 0 to 11
var to = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var check = new Date(c[2], parseInt(c[1])-1, c[0]);
console.log(check > from && check < to)
Instead of comparing the dates directly, compare the getTime() value of the date. The getTime() function returns the number of milliseconds since Jan 1, 1970 as an integer-- should be trivial to determine if one integer falls between two other integers.
Something like
if((check.getTime() <= to.getTime() && check.getTime() >= from.getTime())) alert("date contained");
Try what's below. It will help you...
Fiddle : http://jsfiddle.net/RYh7U/146/
Script :
if(dateCheck("02/05/2013","02/09/2013","02/07/2013"))
alert("Availed");
else
alert("Not Availed");
function dateCheck(from,to,check) {
var fDate,lDate,cDate;
fDate = Date.parse(from);
lDate = Date.parse(to);
cDate = Date.parse(check);
if((cDate <= lDate && cDate >= fDate)) {
return true;
}
return false;
}
The answer that has 50 votes doesn't check for date in only checks for months. That answer is not correct. The code below works.
var dateFrom = "01/08/2017";
var dateTo = "01/10/2017";
var dateCheck = "05/09/2017";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");
var from = new Date(d1); // -1 because months are from 0 to 11
var to = new Date(d2);
var check = new Date(c);
alert(check > from && check < to);
This is the code posted in another answer and I have changed the dates and that's how I noticed it doesn't work
var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "07/07/2013";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");
var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); // -1 because months are from 0 to 11
var to = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var check = new Date(c[2], parseInt(c[1])-1, c[0]);
alert(check > from && check < to);
Simplified way of doing this based on the accepted answer.
In my case I needed to check if current date (Today) is pithing the range of two other dates so used newDate() instead of hardcoded values but you can get the point how you can use hardcoded dates.
var currentDate = new Date().toJSON().slice(0,10);
var from = new Date('2020/01/01');
var to = new Date('2020/01/31');
var check = new Date(currentDate);
console.log(check > from && check < to);
I have created customize function to validate given date is between two dates or not.
var getvalidDate = function(d){ return new Date(d) }
function validateDateBetweenTwoDates(fromDate,toDate,givenDate){
return getvalidDate(givenDate) <= getvalidDate(toDate) && getvalidDate(givenDate) >= getvalidDate(fromDate);
}
Here is a Date Prototype method written in typescript:
Date.prototype.isBetween = isBetween;
interface Date { isBetween: typeof isBetween }
function isBetween(minDate: Date, maxDate: Date): boolean {
if (!this.getTime) throw new Error('isBetween() was called on a non Date object');
return !minDate ? true : this.getTime() >= minDate.getTime()
&& !maxDate ? true : this.getTime() <= maxDate.getTime();
};
I did the same thing that #Diode, the first answer, but i made the condition with a range of dates, i hope this example going to be useful for someone
e.g (the same code to example with array of dates)
var dateFrom = "02/06/2013";
var dateTo = "02/09/2013";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); // -1 because months are from 0 to 11
var to = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var dates= ["02/06/2013", "02/07/2013", "02/08/2013", "02/09/2013", "02/07/2013", "02/10/2013", "02/011/2013"];
dates.forEach(element => {
let parts = element.split("/");
let date= new Date(parts[2], parseInt(parts[1]) - 1, parts[0]);
if (date >= from && date < to) {
console.log('dates in range', date);
}
})
Try this:
HTML
<div id="eventCheck"></div>
JAVASCRIPT
// ----------------------------------------------------//
// Todays date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
// Add Zero if it number is between 0-9
if(dd<10) {
dd = '0'+dd;
}
if(mm<10) {
mm = '0'+mm;
}
var today = yyyy + '' + mm + '' + dd ;
// ----------------------------------------------------//
// Day of event
var endDay = 15; // day 15
var endMonth = 01; // month 01 (January)
var endYear = 2017; // year 2017
// Add Zero if it number is between 0-9
if(endDay<10) {
endDay = '0'+endDay;
}
if(endMonth<10) {
endMonth = '0'+endMonth;
}
// eventDay - date of the event
var eventDay = endYear + '/' + endMonth + '/' + endDay;
// ----------------------------------------------------//
// ----------------------------------------------------//
// check if eventDay has been or not
if ( eventDay < today ) {
document.getElementById('eventCheck').innerHTML += 'Date has passed (event is over)'; // true
} else {
document.getElementById('eventCheck').innerHTML += 'Date has not passed (upcoming event)'; // false
}
Fiddle:
https://jsfiddle.net/zm75cq2a/
Suppose for example your date is coming like this & you need to install momentjs for advance date features.
let cmpDate = Thu Aug 27 2020 00:00:00 GMT+0530 (India Standard Time)
let format = "MM/DD/YYYY";
let startDate: any = moment().format(format);
let endDate: any = moment().add(30, "days").format(format);
let compareDate: any = moment(cmpDate).format(format);
var startDate1 = startDate.split("/");
var startDate2 = endDate.split("/");
var compareDate1 = compareDate.split("/");
var fromDate = new Date(startDate1[2], parseInt(startDate1[1]) - 1, startDate1[0]);
var toDate = new Date(startDate2[2], parseInt(startDate2[1]) - 1, startDate2[0]);
var checkDate = new Date(compareDate1[2], parseInt(compareDate1[1]) - 1, compareDate1[0]);
if (checkDate > fromDate && checkDate < toDate) {
... condition works between current date to next 30 days
}
This may feel a bit more intuitive. The parameter is just a valid date string.
This function returns true if the date passed as argument is in the current week, or false if not.
function isInThisWeek(dateToCheck){
// Create a brand new Date instance
const WEEK = new Date()
// create a date instance with the function parameter
//(format should be like dd/mm/yyyy or any javascript valid date format )
const DATEREF = new Date(dateToCheck)
// If the parameter is a not a valid date, return false
if(DATEREF instanceof Date && isNaN(DATEREF)){
console.log("invalid date format")
return false}
// Get separated date infos (the date of today, the current month and the current year) based on the date given as parameter
const [dayR, monthR, yearR] = [DATEREF.getDate(), DATEREF.getMonth(), DATEREF.getFullYear()]
// get Monday date by substracting the day index (number) in the week from the day value (count)
//in the month (like october 15th - 5 (-> saturday index)) and +1 because
//JS weirdly starts the week on sundays
const monday = (WEEK.getDate() - WEEK.getDay()) + 1
// get Saturday date
const sunday = monday + 6
// Start verification
if (yearR !== WEEK.getFullYear()) { console.log("WRONG YEAR"); return false }
if (monthR !== WEEK.getMonth()) { console.log("WRONG MONTH"); return false }
if(dayR >= monday && dayR <= sunday) { return true }
else {console.log("WRONG DAY"); return false}
}
Try this
var gdate='01-05-2014';
date =Date.parse(gdate.split('-')[1]+'-'+gdate.split('-')[0]+'-'+gdate.split('-')[2]);
if(parseInt(date) < parseInt(Date.now()))
{
alert('small');
}else{
alert('big');
}
Fiddle
This question is very generic, hence people who are using date libraries also check for the answer, but I couldn't find any answer for the date libraries, hence I am posting the answer for Luxon users.
const fromDate = '2022-06-01T00:00:00.000Z';
const toDate = '2022-06-30T23:59:59.999Z';
const inputDate = '2022-08-09T20:26:13.380Z';
if (
DateTime.fromISO(inputDate) >= DateTime.fromISO(fromDate) &&
DateTime.fromISO(inputDate) <= DateTime.fromISO(toDate)
) {
console.log('within range');
} else {
console.log('not in range');
}

javascript date validation - checking two dates

i have two input box for getting date value in the format "dd/mm/yyyy".
i have to create coupon for a shop, so i have to check 1st date should be from tomorrow.
for ex. if today is 5th sep, then 1st date should not be before 6th sep.
and 2nd date should be atleast 1day greater than the 1st date. if user entered 1st date as 10th sep, then 2nd date should not be same or before 10th sep.
so if a user enters 31st jan 2013 ( 31/01/2013) as 1st date then 2nd date can be 1st feb or any date after 1st feb. so i hvae to check the date validation also.
for date validation i am using the following code -
function chkdate(y,m,d)
{
var date = new Date(y,m-1,d);
month1 = date.getMonth()+1;
date1 =date.getDate();
if(month1 <10)
{
month1 = "0"+month1;
}
if(date1 <10)
{
date1 = "0"+date1;
}
var convertedDate =""+date.getFullYear() + (month1) + date1;
var givenDate = "" + y + m + d;
return ((givenDate==convertedDate)?true:false);
}
i am callling above function inside a function -
function generate_coupon()
{
var f_arr = from_date.split("/"); //from_date is from 1st input date value.
var f_day = f_arr[0];
var f_month =f_arr[1];
var f_year =f_arr[2];
var t_arr = to_date.split("/"); //to_date is from 2nd input date value.
var t_day = t_arr[0];
var t_month =t_arr[1];
var t_year =t_arr[2];
if (chkdate(f_year,f_month,f_day)== true && chkdate(t_year,t_month,t_day)== true)
{
}
else
{
alert('Enter Valid Date - dd/mm/yyyy');
}
}
in that if condition i have to check both date values - the 1st date value is from tomorrow or not and 2nd date value should differ from 1st date by atleast 1 day. if both conditions are true then i wil generate a coupon or else i will alert invalid date.
how should i do it ??
rather doing this type of validation, i think it will be more easy for you that you fill the other date field you self using some defined code. and made those fields UN-editable
Farid has made a good point, however if your base date is dynamic something like this should work:
function isValidInput(date1, date2) {
return date2 >= getNextDate(date1);
}
function getNextDate(date) {
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24;
var date_ms = date.getTime();
var nextDate_ms = date_ms + ONE_DAY;
var nextDate = new Date(nextDate_ms);
// Make sure to get rid of time, so that it's always at 00:00:00 hour.
return new Date(nextDate.getYear(), nextDate.getMonth(), nextDate.getYear());
}
function checkDates(d1, d2) {
if (d1 instanceof Date && d2 instanceof Date) {
var today = new Date();
today.setHours(0, 0, 0, 0);
if (date1.getTime() < (today.getTime() + 86400000)) {
return "First date should be after today";
}
if (date2.getTime() < (date1.getTime() + 86400000)) {
return "Second date should be after First date";
}
return "Dates are valid";
}
return "One or more invalid date";
}
var date1Str = "6/9/2012";
var date2Str = "7/9/2012";
var date1Arr = date1Str.split("/");
var date2Arr = date2Str.split("/");
var date1 = new Date(date1Arr[2], date1Arr[1] - 1, date1Arr[0]);
var date2 = new Date(date2Arr[2], date2Arr[1] - 1, date2Arr[0]);
alert(checkDates(date1, date2));
Try this
function generate_coupon() {
var from_date = document.getElementById("fromDate");
var to_date = document.getElementById("toDate");
var from = new Date(from_date.value);
var to = new Date(to_date.value);
var today = new Date();
var tomorrow = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
if (from >= tomorrow && to > from) {
} else {
alert('Enter Valid Date - dd/mm/yyyy');
}
}​

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