Javascript Data function to disable specific date - javascript

I have requirement to disable tuesday and thursday on this calendar function but it should enable the current date also. Below script will disable past dates and enable only tuesday and thursday but current date is not enabled. i need to enable current date selection and only future tuesday & thursday dates only.
function datefunc(date) {
var today = new Date();
if (date != null) {
var yesterday = new Date();
var futureDate = new Date();
var today = new Date();
today = today.setDate(today.getDate() - 1)
yesterday = yesterday.setDate(yesterday.getDate() - 1);
futureDate = futureDate.setDate(futureDate.getDate() + 1);
if (date < yesterday)
return true;
else if (date == today || date.getDay() != 2 && date.getDay() != 4)
return true;
}
return false;
}

I am going to go ahead and attempt to answer a very ambiguous question. Given that, I am only going to post something that hopefully you can work with.
First off, this date stuff is "hard" so let's leverage StackOverflow to find stuff we can work with (it MIGHT be better to use a date library but let's build from others efforts - up vote them as useful!)
Some additional information on date comparisons: https://stackoverflow.com/a/493018/125981
// credit here: https://stackoverflow.com/a/1353711/125981
function isDate(d) {
if (Object.prototype.toString.call(d) === "[object Date]") {
// it is a date
if (isNaN(d.getTime())) { // d.valueOf() could also work
// date is not valid
return false;
} else {
// date is valid
return true;
}
} else {
// not a date
return false;
}
}
// return true if prior to yesterday, OR is today(exactly), is not tuesday, or is not thursday
function datefunc(date) {
var today = new Date();
if (isDate(date)) {
var yesterday = new Date(new Date().setDate(today.getDate() - 1));
var tomorrow = new Date(new Date().setDate(today.getDate() + 1));
console.log(today.getTime(), yesterday.getTime(), tomorrow.getTime());
if (date.getTime() < yesterday.getTime() || date.getTime() == today.getTime() || (date.getDay() != 2 && date.getDay() != 4)) {
return true;
}
}
return false;
}
// credit here: https://stackoverflow.com/a/27336600/125981
// if d is dow, return that else next dow
function currentOrNexDowDay(d, dow) {
d.setDate(d.getDate() + (dow + (7 - d.getDay())) % 7);
return d;
}
// credit here: https://stackoverflow.com/a/27336600/125981
// if cd is dow and not d, return that else next dow
function nextDowDay(d, dow) {
var cd = new Date(d);
cd.setDate(cd.getDate() + (dow + (7 - cd.getDay())) % 7);
if (d.getTime() === cd.getTime()) {
cd.setDate(cd.getDate() + 7);
}
return cd;
}
// a Tuesday
var checkDate = new Date("2018-02-13T17:30:29.569Z");
console.log(datefunc(checkDate));
// a Wednesday
checkDate = new Date("2018-02-14T17:30:29.569Z");
console.log(datefunc(checkDate));
// a Sunday
checkDate = new Date("2018-02-11T17:30:29.569Z");
console.log(datefunc(checkDate));
// Next Monday
var d = new Date();
d = currentOrNexDowDay(d, 1);
//d.setDate(d.getDate() + (8 - d.getDay()) % 7);
console.log(d);
console.log(datefunc(d));
// Next Tuesday
var dt = new Date();
dt = nextDowDay(dt, 2);
console.log(dt);
console.log(datefunc(dt));

Related

js datepicker - allow non-consecutive days pcm

I would like to limit users to selecting only the first and third Monday of each month. We have a volunteer intake only on these days, so I want to limit incorrect date selections as much as possible.
I'm not a js coder, but have managed to adapt some code I found online to allow the first or third Monday of each month, but I can't work out how to allow both of them.
Here's the code I have for the first Monday:
var firstMonday = new Date(date);
var mondays=0;
firstMonday.setDate(1);
while (mondays < 1) {
firstMonday.setDate(firstMonday.getDate() + 1);
if (firstMonday.getDay() == 1) {
mondays++;
}
}
var result = date.getDate() != firstMonday.getDate();
I think this is what you are asking. Credit to jabclab for the getMondays() function.
// test: first monday of this month
// result: true
//var dates = [new Date(2017,8,4)];
// test: third monday of this month
// result: true
//var dates = [new Date(2017,8,18)];
// test: first and third monday of this month
// result: true
var dates = [new Date(2017,8,4), new Date(2017,8,18)];
// test: first monday, third monday, and random day from this month
// result: false
//var dates = [new Date(2017,8,4), new Date(2017,8,18), new Date(2017,8,22)];
alert(validate(dates));
function validate(dates) {
var valid = true;
var mondays = getMondays();
var firstMonday = mondays[0].setHours(0,0,0,0);
var thirdMonday = mondays[2].setHours(0,0,0,0);
if (dates && dates.length > 0) {
for (var i = 0; i < dates.length; i++) {
// Zero out time so only year, month, and day is compared
var d = dates[i].setHours(0,0,0,0);
if (d != firstMonday && d != thirdMonday) {
return false;
}
}
}
else {
valid = false;
}
return valid;
}
function getMondays() {
var d = new Date(),
month = d.getMonth(),
mondays = [];
d.setDate(1);
// Get the first Monday in the month
while (d.getDay() !== 1) {
d.setDate(d.getDate() + 1);
}
// Get all the other Mondays in the month
while (d.getMonth() === month) {
mondays.push(new Date(d.getTime()));
d.setDate(d.getDate() + 7);
}
return mondays;
}
Thanks, but I'm not sure if the above works or not as I was looking for a js code answer - I'll leave that for someone else to work out.
...which I've found in the meantime. Many thanks to Hugh at Fabrik for the following:
var thisdate = new Date(date);
thisdate.setHours(0,0,0,0);
var day = 1; // monday
var nth = 1; // first
var first = new Date(thisdate.getFullYear(), thisdate.getMonth(), 1),
add = (day - first.getDay() + 7) % 7 + (nth - 1) * 7;
first.setDate(1 + add);
nth = 3; // third
var third = new Date(thisdate.getFullYear(), thisdate.getMonth(), 1),
add = (day - third.getDay() + 7) % 7 + (nth - 1) * 7;
third.setDate(1 + add);
//console.log(thisdate + ', ' + first + ', ' + third);
var result = (first.getTime() !== thisdate.getTime()) && (third.getTime() !== thisdate.getTime());

How to check if date is 3 days before current date

I have this Javascript code, where I have a condition for 3 days after the current date and one for the current day. I would need to add a condition for 3 days previous to the current date. How can I do that?
$('.entry-date').each(function() {
var dateString = $(this).text();
var parts = dateString.split("-");
var date = new Date(parseInt(parts[2]), parseInt(parts[1])-1, parts[0]);
var now = new Date();
var diff = dateDiffInDays(now, date);
if ((diff < 3) && (diff > 0)) {
$(this).parent().addClass("new-entry");
}
if (diff == 0) {
$(this).parent().addClass("today");
}
});

JavaScript application for showing the weekend dates?

I thought a lot - I tried but I could not solve it. I need a JavaScript application that shows the nearest weekend dates in the current date.
If it's a weekend now, give it the dates of this weekend, if not, then next weekend's dates.
I'm waiting for your help.
Respects.
You can use the built-in Date constructor.
var date = new Date();
var day = date.getDay();
var saturday;
var sunday;
if(day === 0 || day === 6){ //0 for Sunday, 6 for Saturday
saturday = date;
sunday = new Date(saturday.getTime());
sunday.setDate(saturday.getDate() + (day === 0 ? -1 : 1));
if(day === 0){
var temp = saturday;
saturday = sunday; //Confusing, but they are actually the wrong dates, so we are switching the dates
sunday = temp;
temp = null; //Free up some memory!
}
}
else{
//This is the complicated part, we need to find when is the next Saturday
saturday = new Date(date.getFullYear(), date.getMonth(), (date.getDate() + 6) - day);
sunday = new Date(saturday.getTime());
sunday.setDate(saturday.getDate() + (saturday.getDay() === 0 ? -1 : 1));
}
date = day = null; //Free up some memory!
document.body.innerText = [saturday, sunday];
To get the date, use saturday.getDate() or sunday.getDate().Remember that Date months are 0-based. See here for more info.
var chosenDay = new Date();
var box = [];
var counting = 0;
for (var i = 0; i < 7; i++) {
chosenDay.setDate(chosenDay.getDate() + counting);
var day = chosenDay.getDate();
var dayy = chosenDay.getDay();
var month = chosenDay.getMonth()+1;
var year = chosenDay.getFullYear();
box.push({day: day, dayy: dayy});
counting = 1;
};
Now to find Saturday and Sunday
box.map(function(obj) {
if (obj.dayy === 6) {
console.log('Saturday found');
alert(obj.day);
};
if (obj.dayy === 0) {
console.log('Sunday found');
alert(obj.day);
};
});
I interpret the "nearest" weekend as being the previous weekend for Monday and Tuesday, and the next weekend for Thursday and Friday. You didn't provide any information on what to do with Wednesday.
However, from other answers it seems you want either the current weekend for Saturday and Sunday and or the next weekend for weekdays.
The following is a little more concise than other answers:
/* Get nearest weekend to the provided date
** #param {Date} date - date to get weekends nearst to
** #returns {Array} array of Dates [Saturday, Sunday]
*/
function getNearestWeekend(date) {
// Copy date so don't mess with provided date
var d = new Date(+date);
// If weekday, move d to next Saturday else to current weekend Saturday
if (d.getDay() % 6) {
d.setDate(d.getDate() + 6 - d.getDay());
} else {
d.setDate(d.getDate() - (d.getDay()? 0 : 1));
}
// Return array with Dates for Saturday, Sunday
return [new Date(d), new Date(d.setDate(d.getDate() + 1))]
}
// Some tests
[new Date(2017,0,7), // Sat 7 Jan
new Date(2017,0,8), // Sun 8 Jan
new Date(2017,0,9), // Mon 9 Jan
new Date(2017,0,12) // Thu 12 Jan
].forEach(function(d) {
var opts = {weekday:'short', day:'numeric', month:'short'};
console.log('Date: ' + d.toLocaleString('en-GB',opts) + ' | Next weekend: ' +
getNearestWeekend(d).map(d =>d.toLocaleString('en-GB',opts)).join(' and ')
);
});

Check if weekend exist in date range using javascript

Wondering if anyone has a solution for checking if a weekend exist between two dates and its range.
var date1 = 'Apr 10, 2014';
var date2 = 'Apr 14, 2014';
funck isWeekend(date1,date2){
//do function
return isWeekend;
}
Thank you in advance.
EDIT Adding what I've got so far. Check the two days.
function isWeekend(date1,date2){
//do function
if(date1.getDay() == 6 || date1.getDay() == 0){
return isWeekend;
console.log("weekend")
}
if(date2.getDay() == 6 || date2.getDay() == 0){
return isWeekend;
console.log("weekend")
}
}
Easiest would be to just iterate over the dates and return if any of the days are 6 (Saturday) or 0 (Sunday)
Demo: http://jsfiddle.net/abhitalks/xtD5V/1/
Code:
function isWeekend(date1, date2) {
var d1 = new Date(date1),
d2 = new Date(date2),
isWeekend = false;
while (d1 < d2) {
var day = d1.getDay();
isWeekend = (day === 6) || (day === 0);
if (isWeekend) { return true; } // return immediately if weekend found
d1.setDate(d1.getDate() + 1);
}
return false;
}
If you want to check if the whole weekend exists between the two dates, then change the code slightly:
Demo 2: http://jsfiddle.net/abhitalks/xtD5V/2/
Code:
function isFullWeekend(date1, date2) {
var d1 = new Date(date1),
d2 = new Date(date2);
while (d1 < d2) {
var day = d1.getDay();
if ((day === 6) || (day === 0)) {
var nextDate = d1; // if one weekend is found, check the next date
nextDate.setDate(d1.getDate() + 1); // set the next date
var nextDay = nextDate.getDay(); // get the next day
if ((nextDay === 6) || (nextDay === 0)) {
return true; // if next day is also a weekend, return true
}
}
d1.setDate(d1.getDate() + 1);
}
return false;
}
You are only checking if the first or second date is a weekend day.
Loop from the first to the second date, returning true only if one of the days in between falls on a weekend-day:
function isWeekend(date1,date2){
var date1 = new Date(date1), date2 = new Date(date2);
//Your second code snippet implies that you are passing date objects
//to the function, which differs from the first. If it's the second,
//just miss out creating new date objects.
while(date1 < date2){
var dayNo = date1.getDay();
date1.setDate(date1.getDate()+1)
if(!dayNo || dayNo == 6){
return true;
}
}
}
JSFiddle
Here's what I'd suggest to test if a weekend day falls within the range of two dates (which I think is what you were asking):
function containsWeekend(d1, d2)
{
// note: I'm assuming d2 is later than d1 and that both d1 and d2 are actually dates
// you might want to add code to check those conditions
var interval = (d2 - d1) / (1000 * 60 * 60 * 24); // convert to days
if (interval > 5) {
return true; // must contain a weekend day
}
var day1 = d1.getDay();
var day2 = d2.getDay();
return !(day1 > 0 && day2 < 6 && day2 > day1);
}
fiddle
If you need to check if a whole weekend exists within the range, then it's only slightly more complicated.
It doesn't really make sense to pass in two dates, especially when they are 4 days apart. Here is one that only uses one day which makes much more sense IMHO:
var date1 = 'Apr 10, 2014';
function isWeekend(date1){
var aDate1 = new Date(date1);
var dayOfWeek = aDate1.getDay();
return ((dayOfWeek == 0) || (dayOfWeek == 6));
}
I guess this is the one what #MattBurland sugested for doing it without a loop
function isWeekend(start,end){
start = new Date(start);
if (start.getDay() == 0 || start.getDay() == 6) return true;
end = new Date(end);
var day_diff = (end - start) / (1000 * 60 * 60 * 24);
var end_day = start.getDay() + day_diff;
if (end_day > 5) return true;
return false;
}
FIDDLE
Whithout loops, considering "sunday" first day of week (0):
Check the first date day of week, if is weekend day return true.
SUM "day of the week" of the first day of the range and the number of days in the lap.
If sum>5 return true
Use Date.getDay() to tell if it is a weekend.
if(tempDate.getDay()==6 || tempDate.getDay()==0)
Check this working sample:
http://jsfiddle.net/danyu/EKP6H/2/
This will list out all weekends in date span.
Modify it to adapt to requirements.
Good luck.

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

Categories

Resources