Check if date is in the past Javascript - 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;
}
}
}

Related

Date object doesn't exist after definition?

I'm trying to make a function that returns an array of dates in between two dates. This is my code:
Date.prototype.addDays = function(days)
{
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
function getdaterange(startdate, enddate)
{
var s = new Date(startdate);
var e = new Date(enddate);
var datearray = [s];
var done = false;
while(!done)
{
var date = datearray.pop().addDays(1);
if (date == e)
{
datearray.push(date);
done = true;
}
}
}
getdaterange("2018-09-01", "2018-09-25");
The function isn't done yet, but when I try to manipulate the date object on the line that sets the variable "date", it comes back as undefined or says that .pop() isn't a method of Date. I've tried several different configurations. (Where I change how I am manipulating the date object. For example: defining the variable and then calling the .addDays() method afterwards.)
This is just one of them. Does anybody know whats going on?
Thanks for any help in advanced.
Thanks for your help from the comments. Edited Code:
Date.prototype.addDays = function(days)
{
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
function getdaterange(startdate, enddate)
{
var s = new Date(startdate);
var e = new Date(enddate);
var datearray = [s];
var done = false;
while(!done)
{
var temp = datearray;
var date = temp.pop().addDays(1);
if (date.valueOf() == e.valueOf())
{
datearray.push(date);
done = true;
}
else
{
datearray.push(date);
}
}
return datearray;
}
console.log(getdaterange("2018-09-01", "2018-09-25"));
Rather than trying to 'extend' the Date class, you can encapsulate the desired logic in it's own class as follows
class DateUtil {
static addDays(date, days) {
return date.setDate(date.getDate() + days)
}
static getDateRange(dateStart, dateEnd) {
let date = new Date(dateStart);
let endDate = new Date(dateEnd);
let dates = [];
while (date < endDate) {
dates.push(new Date(this.addDays(date, 1)))
}
return dates;
}
}
DateUtil.getDateRange('2018-09-01', '2018-09-25')
.forEach(date => console.log(date.toString()));
What I ended up needing to do (after fixing the first problem) was set var temp equal to var datearray through a method like Array.from(). That way temp wasn't pointing to datearray directly and I always ended up with one item in the array.
Date.prototype.addDays = function(days)
{
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
function getdaterange(startdate, enddate)
{
var s = new Date(startdate);
var e = new Date(enddate);
var datearray = [s];
var done = false;
while(!done)
{
var temp = Array.from(datearray);
var date = temp.pop().addDays(1);
if (date.valueOf() == e.valueOf())
{
datearray.push(date);
done = true;
}
else
{
datearray.push(date);
}
}
return datearray;
}

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

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

Check if a date within in range

I am trying to check if a date of format mm.dd.yyyy is greater than today and less than the date after 6 months from today.
Here is my code:
var isLinkExpiryDateWithinRange = function(value) {
var monthfield = value.split('.')[0];
var dayfield = value.split('.')[1];
var yearfield = value.split('.')[2];
var inputDate = new Date(yearfield, monthfield - 1, dayfield);
var today = new Date();
today = new Date(today.getFullYear(), today.getMonth(), today.getDate());
alert(inputDate > today);//alert-> true
var endDate = today;
endDate.setMonth(endDate.getMonth() + 6);
alert(inputDate > today);//alert-> false
if(inputDate > today && inputDate < endDate) {
alert('1');
} else {
alert('2');/always alert it
}
}
If I execute isLinkExpiryDateWithinRange('12.08.2012') I wish it will show 1 as this is within the range, but it is displaying 2. Moreover the first alert is showing true and the second one false.
Can anyone please explain what is happening?
Change:
var endDate = today;
to:
var endDate = new Date(today);
See the posts here for how objects are referenced and changed. There are some really good examples that help explain the issue, notably:
Instead, the situation is that the item passed in is passed by value.
But the item that is passed by value is itself a reference.
JSFiddle example
function isLinkExpiryDateWithinRange( value ) {
// format: mm.dd.yyyy;
value = value.split(".");
var todayDate = new Date(),
endDate = new Date( todayDate.getFullYear(), todayDate.getMonth() + 6, todayDate.getDate() +1 );
date = new Date(value[2], value[0]-1, value[1]);
return todayDate < date && date < endDate;
}
isLinkExpiryDateWithinRange("12.24.2012"); // true
isLinkExpiryDateWithinRange("12.24.2020"); // false
Below function checks if date selected is within 5 days from today. Date format used is "DD-MM-YYYY", you can use any format by changing value.split('-')[1] order and split character.
function showMessage() {
var value = document.getElementById("invoiceDueDate").value;
var inputDate = new Date(value.split('-')[2], value.split('-')[1] - 1, value.split('-')[0]);
var endDate = new Date();
endDate.setDate(endDate.getDate() + 5);// adding 5 days from today
if(inputDate < endDate) {
alert("If the due date selected for the invoice is within 5 days, and express settlement fee will apply to this transaction.");
}
}

javascript check end date is greater than or equal to start date

Is it possible to check whether an end date is greater than or equal to a start date in Javascript? My dates are strings in the format 'dd/mm/yyyy'.
try this
var startDate = "05/01/2011";
var endDate = "09/01/2011";
var regExp = /(\d{1,2})\/(\d{1,2})\/(\d{2,4})/;
if(parseInt(endDate.replace(regExp, "$3$2$1")) > parseInt(startDate.replace(regExp, "$3$2$1"))){
alert("greater");
}
If the string format ('dd/mm/yyyy') doesn't change, this function should work:
function endAfterStart(start,end){
return new Date(start.split('/').reverse().join('/')) <
new Date(end.split('/').reverse().join('/'));
}
alert(endAfterStart('05/01/2011','09/01/2011')); //=> true
Or extend the Date.prototype:
Date.prototype.isBefore = Date.prototype.isBefore || function(dat){
return this < dat;
}
new Date('05/01/2011'.split('/').reverse().join('/'))
.before( new Date('09/01/2011'.split('/').reverse().join('/')) ); //=>true
Most simple way to do this.
function endAfterStart(start, end) {
var startDate = new Date(start);
var endDate = new Date(end);
return endDate.getTime() >= startDate.getTime();
}
function isDate(value)
{
var fromDate = document.getElementById("fromDate").value
var toDate= document.getElementById("toDate").value
//var curr_Date= new SimpleDateFormat("dd/mm/yyyy");
var dateRegEx = null;
dateRegEx = new RegExp(/^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g);
if (dateRegEx.test(fromDate)){
}
else{
alert("Invalid from date");
return false;
}
dateRegEx = new RegExp(/^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g);
if(dateRegEx.test(toDate)) {
}
else{
alert("Invalid to date");
return false;
}
var stDate = new Date(fromDate);
var enDate = new Date(toDate);
var compDate = enDate - stDate;
//var fdate=enDate-curr_Date;
if(compDate >= 0)
return true;
else
{
alert("To Date cannot be smaller than From Date");
return false;
}
/**/
}
This will work for Leap years also..in dd/mm/yyyy format(not any other format).
Took me some time to find, but JQuery implements this exact functionality with DatePicker date-range. (Source code available in link as well.)
Moment.js also handles date comparisons very well using the diff function.
check out this function
function CompareDates()
{
var str1 = document.getElementById("Fromdate").value;
var str2 = document.getElementById("Todate").value;
var dt1 = parseInt(str1.substring(0,2),10);
var mon1 = parseInt(str1.substring(3,5),10);
var yr1 = parseInt(str1.substring(6,10),10);
var dt2 = parseInt(str2.substring(0,2),10);
var mon2 = parseInt(str2.substring(3,5),10);
var yr2 = parseInt(str2.substring(6,10),10);
var date1 = new Date(yr1, mon1, dt1);
var date2 = new Date(yr2, mon2, dt2);
if(date2 < date1)
{
alert("To date cannot be greater than from date");
return false;
}
else
{
alert("Submitting ...");
document.form1.submit();
}
}
Try this,
function isDateCompare(){
var leadDate = document.getElementById('strDate').value;
var closeDate = document.getElementById('strDateClosed').value;
var date1 = new Date();
date1.setFullYear(leadDate.substr(6,4),(leadDate.substr(3,2)-1),leadDate.substr(0,2));
var date2 = new Date();
date2.setFullYear(closeDate.substr(6,4),(closeDate.substr(3,2)-1),closeDate.substr(0,2));
if (date1> date2)
{
alert("Expected Closed date cannot be less than Lead date.");
return false;
}
else
{
alert("true");
return false;
}
}
First use this function will convert string to Date type in js:
function common_getDateFromUI(str) {
var arr = str.split("/");
var returnDate = new Date(arr[2], arr[1] - 1, arr[0], 0, 0, 0, 0);
return returnDate;
}
Second: after you get the javascript date type, you just compare it as normal type like date1 > date2 or date1 == date2.
Or use this function to get the difference date between date:
function CalendarDays(startDate, endDate) {
if (endDate < startDate)
return 0;
// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0, 0, 0, 1); // Start just after midnight
endDate.setHours(23, 59, 59, 999); // End just before midnight
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.round(diff / millisecondsPerDay);
return days;
}
Follow this link is a simple demo to get difference days between dates. Link demo here
if (iForm.DiddfromDate.value == "")
{
alert(" Please enter a value");
iForm.DiddfromDate.focus();
return false;
}
if (iForm.DiddtoDate.value == "")
{
alert(" Please enter a value");
iForm.DiddtoDate.focus();
return false;
}
try {
var d1 = iForm.DiddfromDate.value.substr(0, 2);
var m1 = iForm.DiddfromDate.value.substr(3, 2);
var y1 = iForm.DiddfromDate.value.substr(6, 4);
var StrDate = m1 + "/" + d1 + "/" + y1;
var d2 = iForm.DiddtoDate.value.substr(0, 2);
var m2 = iForm.DiddtoDate.value.substr(3, 2);
var y2 = iForm.DiddtoDate.value.substr(6, 4);
var EndDate = m2 + "/" + d2 + "/" + y2;
var startDate = new Date(StrDate);
var endDate = new Date(EndDate);
if (startDate > endDate) {
alert('To date should be greater than From date.');
iForm.DiddfromDate.value = '';
iForm.DiddtoDate.value = '';
iForm.DiddfromDate.focus();
return false;
}
} catch (e) { alert(e.Description); }
return true;
Just convert the string to date and use getTime method of Date object to compare it.
Example code
var startDate = '04/04/2015'; //date in dd/mm/yyyy format
var endDate = '05/04/2015';
function compareDates(sDate, eDate) {
var dateTime1 = new Date(sDate).getTime(),
dateTime2 = new Date(eDate).getTime();
var diff = dateTime2 - dateTime1;
if (diff > 0) {
alert("endDate is greater than startDate");
return true;
}
}
compareDates(startDate, endDate);
Working Fiddle

Categories

Resources