JS - Date check - javascript

I'm trying to check if a date (from a date input) is different than today :
<input type="date" id="date">
Here my JS :
var selectedDate = document.getElementById('date');
var now = new Date();
if (selectedDate < now) {
alert("Some alert!");
return;
}
It doesn't work - any idea why ?
Thanks

Here the solution :
var selectedDate = document.getElementById('date').value;
var date = new Date(selectedDate);
var now = new Date();
if (date < now) {
alert("You picked an invalid date!");
return;
}

Related

the function is not alerting something

using this code to check if the user is over 18 years age or not. but the function is alerting only "you are not 18+". also there is no error in console
for ex:- 23/12/1500 23/12/2008
var dob = document.getElementById("dob").value;
var jsdate = new Date(dob);
var jsdatearray = jsdate.toString().split("/");
var day = jsdatearray[0];
var month = jsdatearray[1];
var year = jsdatearray[2];
var nowdate = new Date();
nowdate.setFullYear(year, month - 1, day);
var maxDate = new Date();
maxDate.setYear(maxDate.getYear() - 18);
if (maxDate < nowdate) {
alert('you are 18+');
}
else {
alert('you are not 18+');
}
There were a few things off in the code. First, the date wasn't correctly imported into the Javascript. Second, the condition checking the date was backward. The code below should work better.
var dob = document.getElementById("dob").value;
var jsdatearray = dob.split("-");
var year = jsdatearray[0];
var day = jsdatearray[1];
var month = jsdatearray[2];
var nowdate = new Date();
nowdate.setFullYear(year, month - 1, day);
var maxDate = new Date();
maxDate.setYear(maxDate.getYear() - 18);
console.log(maxDate < nowdate);
if (maxDate > nowdate) {
alert('you are 18+');
}
else {
alert('you are not 18+');
}

datetime picker, check is today

I'm fetching users input in jquery datetime picker in format like this
2017-02-07 10:05
which is fine. My question is: how can I check is this users input today or not?
After getting suggestion from this question this is how you can do that. First setting the date constructor for today and the test date then set their time portion equal to zero and compare.
There are also other cool plugins to achieve the same more easily and more accurately like dateJs , momentJs
Using momentJs
var inputDate = new Date("2017-02-07 10:05");
var isToday = inputDate.isSame(new Date(), "day");
Using dateJs
var isToday = Date.equals(Date.today(), new Date("2017-02-07 10:05").clearTime());
Using native JavaScript date
var inputDate = new Date("2017-02-07 10:05");
var todaysDate = new Date();
var isToday = (inputDate.setHours(0, 0, 0, 0) == todaysDate.setHours(0, 0, 0, 0));
console.log(isToday);
Simplest Way...
var date = new Date('2017-02-07 10:05');
var now = new Date();
console.log(now.toString().substring(4, 15) == date.toString().substring(4, 15));
How about something like this:
<html>
<head>
</head>
<body>
<script>
var dateString = "2017-02-09 10:05";
var dateObj = new Date(dateString);
var ddSomeDate = dateObj.getDate();
var mmSomeDate = dateObj.getMonth()+1; //January is 0!
var yyyySomeDate = dateObj.getFullYear();
var dateObjToday = new Date();
var ddCurrentDate = dateObjToday.getDate();
var mmCurrentDate = dateObjToday.getMonth()+1; //January is 0!
var yyyyCurrentDate = dateObjToday.getFullYear();
if (ddSomeDate == ddCurrentDate &&
mmSomeDate == mmCurrentDate &&
yyyySomeDate == yyyyCurrentDate)
console.log("Same day");
else
console.log("NOT same day");
</script>
</body>
</html>
Try this is used to check the date is today or not
Here is Jquery code
$('#dp').datepicker({
onSelect: function(dateText) {
var today = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).getTime();
var selected = new Date(dateText).getTime();
if (today > selected) alert('prior to today');
else if (today < selected) alert('after today');
else alert('today');
}
});​
And My html code
<input id="dp"/>
Demo here
http://jsfiddle.net/j08691/yBDVJ/
You must parse the date and use this isDateToday function to check:
var date = new Date('2017-02-07 10:05');
var isToday = isDateToday(date);
function isDateToday(td){
var d = new Date();
return td.getDate() == d.getDate() && td.getMonth() == d.getMonth() && td.getFullYear() == d.getFullYear();
}
you can get the current Date-Month-year by:
var d = new Date();
var date = d.getDate();
var month = d.getMonth();
var year = d.getFullYear();
then match the user selected date, month and year by these values.
Try something like this:
var today = new Date();
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
if (Date.parse(today) == Date.parse(selectedDate)) {
alert('today!');
} else {
alert('not today');
}

Date comparison using jquery

I use the following code to check the date is before today! But when I select today, the condition becomes true!
var fromDate = $('#from').datepicker('getDate');
var toDate = $('#to').datepicker('getDate');
var today = new Date();
if(today >= fromDate || toDate <= today){
alert('Cannot book dates prior to today.');
$('#from, #to').val('')
return false;
}
What am I doing wrong here?
Should be something like
var fromDate = $('#from').datepicker('getDate');
var toDate = $('#to').datepicker('getDate');
var today = new Date();
today.setHours(0,0,0,0);
fromDate.setHours(0,0,0,0);
toDate.setHours(0,0,0,0);
if(today > fromDate || toDate < today){
alert('Cannot book dates prior to today.');
$('#from, #to').val('')
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');
}

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