Related
I have call center and I use this JS code to let messages come in during business hours and after business hours/weekends it display a message saying that is outside of support time, my question is, how I make this code work also for holidays?
exports.handler = async function(context, event, callback) {
const moment = require('moment-timezone');
var now = moment().tz('America/New_York');
console.log('Current time-->'+now);
console.log('current hours-->'+now.hour());
let isWorkingHours = false;
//let isWorkingHours = true; // testing
const weekday = now.isoWeekday();
console.log('weekday-->'+weekday);
if (now.hour() >= 9 && now.hour() <= 17 && weekday <= 5) {
//if (now.hour() >= 4 && now.hour() <= 20 && weekday <= 2) { // testing
isWorkingHours = true;
//Console.log('This is outside working hours');
}
callback(null, {
isWorkingHours: isWorkingHours
});
}
I got this holiday checker from someone else's post here on StackOverflow (I should have documented the link, but I forgot to). You can iterate through all the dates you are interested in to create a complete list of holidays, or just check if a given date is a holiday
function check_holiday (dt_date) {
// check simple dates (month/date - no leading zeroes)
var n_date = dt_date.getDate(),
n_month = dt_date.getMonth() + 1;
var s_date1 = n_month + '/' + n_date;
if ( s_date1 == '1/1' // New Year's Day
|| s_date1 == '6/14' // Flag Day
|| s_date1 == '7/4' // Independence Day
|| s_date1 == '11/11' // Veterans Day
|| s_date1 == '12/25' // Christmas Day
) return true;
// weekday from beginning of the month (month/num/day)
var n_wday = dt_date.getDay(),
n_wnum = Math.floor((n_date - 1) / 7) + 1;
var s_date2 = n_month + '/' + n_wnum + '/' + n_wday;
if ( s_date2 == '1/3/1' // Birthday of Martin Luther King, third Monday in January
|| s_date2 == '2/3/1' // Washington's Birthday, third Monday in February
|| s_date2 == '5/3/6' // Armed Forces Day, third Saturday in May
|| s_date2 == '9/1/1' // Labor Day, first Monday in September
|| s_date2 == '10/2/1' // Columbus Day, second Monday in October
|| s_date2 == '11/4/4' // Thanksgiving Day, fourth Thursday in November
) return true;
// weekday number from end of the month (month/num/day)
var dt_temp = new Date (dt_date);
dt_temp.setDate(1);
dt_temp.setMonth(dt_temp.getMonth() + 1);
dt_temp.setDate(dt_temp.getDate() - 1);
n_wnum = Math.floor((dt_temp.getDate() - n_date - 1) / 7) + 1;
var s_date3 = n_month + '/' + n_wnum + '/' + n_wday;
if ( s_date3 == '5/1/1' // Memorial Day, last Monday in May
) return true;
// misc complex dates
if (s_date1 == '1/20' && (((dt_date.getFullYear() - 1937) % 4) == 0)
// Inauguration Day, January 20th every four years, starting in 1937.
) return true;
if (n_month == 11 && n_date >= 2 && n_date < 9 && n_wday == 2
// Election Day, Tuesday on or after November 2.
) return true;
return false;
}
The logic for checking if an specific instant in time is outside working ours is in your if statement.
I would abstract this in some sort of storage, based on time ranges for holidays or any day off. You could either have a table or cache where to store these holidays (you should load them in advance).
That way, you can do something like:
Search if there's a holiday whose date matches with the current date (matching just date without timestamp, you can use moment's isSame checking just by date)
If there's a match, return isWorkingHours as false
To check if the date matches, you can use this (regardless of current time, it returns true as you're comparing at date level):
console.log(moment('2021-05-10 14:00:00').isSame('2021-05-10', 'day'));
Here's a list of things that you might want to check for:
Weekends
"Static date" holidays (eg: Christmas)
"Variable date" holidays (eg: Easter)
Times (eg: your office opens at 8:00)
/* Function that checks if office is available at a specific date
* #returns {boolean}
*/
function is_office_available (date = new Date()) {
// weekends, or actually any other day of the week
let day = date.getDay();
if ( [0 /*sunday*/, 6 /*saturday*/].includes(day) ) return false;
// "static date" holidays (formatted as 'DD/MM')
let dd_mm = date.getDate() + '/' + (date.getMonth()+1);
if ( ['24/12', '25/12'].includes(dd_mm) ) return false;
// TODO: "variable date" holidays
// specific times
// this logic has to be extended a LOT if, for example, you have
// the office open from 8:30 to 17:30 with a launch break from 12:00 to 13:00 on weekdays
// and from 9:00 to 12:00 only on mondays
let hh = date.getHours();
if (9 < hh || hh > 17) return false;
// if no test returned true then the office is going to be available on that date
return true;
}
You can simply call this function in an if statement.
"Variable date" holidays have a quite a long (and boring) implementation to do and it depends on the ones you have in your country office.
How do I restrict the JQuery Datepicker to show only bi-weekly Saturdays. I have successfully restricted it to show only weekly but could not figure out how to make it bi-weekly. See sample code below for weekly filter that allows for Saturdays only.
$("#datefilter").datepicker({
beforeShowDay: function(date){
if(date.getDay() === 6){
return [true];
}else{
return [false];
}
});
Did not test too much, but this should work for 1st and 3rd Saturday (5th too):
$(function() {
$("#datepicker").datepicker({
beforeShowDay: function(date){
var dayOfMonth = date.getDate()
if(date.getDay() === 6 && Math.floor((dayOfMonth - 1) / 7) % 2 === 0){
return [true];
}else{
return [false];
}
}
});
});
And if you want 2nd and 4th, replace 0 with 1 in 2nd part of if condition:
Math.floor((dayOfMonth - 1) / 7) % 2 === 1
UPDATE corrected calculation, should be (dayOfMonth - 1).
This is another option, if you anticipate needing to change to another day of the week you can seed it with a date that falls on that day:
function isAlternatingDay(testDate){
var seedDay = new Date(2018,11,3);
var daysDiff = (testDate - seedDay)/86400000;
return daysDiff % 14 === 0;
}
This has been asked (badly) before - I don't think the answer in that post really addressed the issue, and then it went stale. I'm going to attempt to ask it again with a clearer demonstration of the issue.
The implementation of Javascript Date.setMonth() appears not to follow the principle of least surprise. Try this in a browser console:
d = new Date('2017-08-31') // Set to last day of August
d.getMonth() // 7 - months are zero-based
d.setMonth(8) // Try to set the month to 8 (September)
d.getMonth() // 9 - October. WTF Javascript?
Similarly:
d = new Date('2017-10-31')
d.getMonth() // 9
d.setMonth(8)
d.getMonth() // 9 (still?)
Firefox on Linux appears even worse - sometimes returning a date in October, and a result from getMonth() which doesn't match that month!
My question (and I think that of the OP from that linked question) is how to consistently implement a 'next' / 'prev' month function in, e.g. a datepicker? Is there a well known way of doing this which doesn't surprise the user by, for example, skipping September when they start on August 31st and click 'next'? Going from January 31st is even more unpredictable currently - you will end up on either March 2nd or March 3rd, depending on whether it's a leap year or not!
My personal view is that the least surprise would be to move to the last day of the next / previous month. But that requires the setMonth() implementation to care about the number of days in the months in question, not just add / subtract a fixed duration. According to this thread, the moment.js approach is to add / subtract the number of milliseconds in 30 days, which suggests that library would be prone to the same inconsistencies.
It's all simple and logic. Lets take your example and go see what id does.
So the first line
d = new Date('2017-08-31') // Set to last day of August
console.log(d); // "2017-08-31T00:00:00.000Z"
console.log(d.getMonth()); // 7 - months are zero-based
So all good so far. Next step: Your comment says it: // Try to set the month to 8 (September) So it's not done with trying. You either set it to september or you don't. In your example you set it to October. Explanation further down.
d = new Date('2017-08-31') // Set to last day of August
console.log(d); // "2017-08-31T00:00:00.000Z"
console.log(d.getMonth()); // 7 - months are zero-based
d.setMonth(8) // Try to set the month to 8 (September)
console.log(d); // but now I see I was wrong it is (October)
So the good question is WHY? From MDN
Note: Where Date is called as a constructor with more than one
argument, if values are greater than their logical range (e.g. 13 is
provided as the month value or 70 for the minute value), the adjacent
value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to
new Date(2014, 1, 1), both create a date for 2014-02-01 (note that the
month is 0-based). Similarly for other values: new Date(2013, 2, 1, 0,
70) is equivalent to new Date(2013, 2, 1, 1, 10) which both create a
date for 2013-03-01T01:10:00.
So that sayd September has only 30 Days but the Date Object has 31. This is why it gives you October and not September.
The simplest will be to take the date you have and set it to first day of month. Something like so:
var d = new Date('2017-08-31') // Set to last day of August
// simplest fix take the date you have and set it to first day of month
d = new Date(d.getFullYear(), d.getMonth(), 1);
console.log(d); // "2017-08-31T00:00:00.000Z"
console.log(d.getMonth()); // 7 - months are zero-based
d.setMonth(8) // Set the month to 8 (September)
console.log(d.getMonth()); // get 8 it is (September)
If setMonth is used when adding and subtracting months, then if the date of the start month doesn't exist in the end month, the extra days cause the date to "roll over" to the next month, so 31 March minus 1 month gives 2 or 3 March.
A simple algorithm is to test the start date and end date and if they differ, set the end date to 0 so it goes to the last day of the previous month.
One issue with this is that subtracting 1 month twice may not give the same result as subtracting 2 months once. 31 March 2017 minus one month gives 28 Feb, minus another month gives 28 Jan. Subtract 2 months from 31 March and you get 31 Jan.
C'est la vie.
function addMonths(date, num) {
var d = date.getDate();
date.setMonth(date.getMonth() + num);
if (date.getDate() != d) date.setDate(0);
return date;
}
// Subtract one month from 31 March
var a = new Date(2017,2,31);
console.log(addMonths(a, -1).toString()); // 28 Feb
// Add one month to 31 January
var b = new Date(2017,0,31);
console.log(addMonths(b, 1).toString()); // 28 Feb
// 29 Feb plus 12 months
var c = new Date(2016,1,29)
console.log(addMonths(c, 12).toString()); // 28 Feb
// 29 Feb minus 12 months
var c = new Date(2016,1,29)
console.log(addMonths(c, -12).toString()); // 28 Feb
// 31 Jul minus 1 month
var d = new Date(2016,6,31)
console.log(addMonths(d, -1).toString()); // 30 Jun
Since getMonth() returns an integer number, you can simply implement a generator over the date object, that sets the month + 1 or - 1 so long as your not at month 11 or month 0 respectively.
function nextMonth(dateObj) {
var month = dateObj.getMonth();
if(month != 11) dateObj.setMonth(month + 1);
return dateObj;
}
function prevMonth(dateObj) {
var month = dateObj.getMonth();
if(month != 0) dateObj.setMonth(month - 1);
return dateObj;
}
If you want to match the days in the previous month you can use an object lookup table.
Now, for your last day of the month problem:
function getLastDayofMonth(month) {
var lookUp = {
0:31,
1:28,
2:30,
3:31
};
return lookUp[month];
}
//and then a revised version
function nextMonth(dateObj) {
var month = dateObj.getMonth();
var day = dateObj.getDate();
if(month != 12) dateObj.setMonth(month + 1);
if(getLastDayofMonth(month)<day)dateObj.setDate(getLastDayofMonth(month));
return dateObj;
}
This should work for incrementing the month, you can use a similar strategy to decrement.
// isLeapYear :: Number -> Boolean
const isLeapYear = ((err) => {
return yr => {
// check for the special years, see https://www.wwu.edu/skywise/leapyear.html
if (yr === 0) {
throw err;
}
// after 8 AD, follows 'normal' leap year rules
let passed = true;
// not technically true as there were 13 LY BCE, but hey.
if (yr === 4 || yr < 0 || (yr % 4)) {
passed = false;
} else {
if (yr % 400) {
if (!(yr % 100)) {
passed = false;
}
}
}
return passed;
};
})(new Error('Year zero does not exist, refers to 1 BCE'));
const daysInMonth = [
31,
28,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
];
// isLastDay :: Number, Number -> Boolean
const isLastDay = (d, m, y) => {
let dm = isLeapYear(y) && m === 1 ? 29 : daysInMonth(m);
return dm === d;
};
// getLastDay :: Number, Number -> Number
const getLastDay = (m, y) => isLeapYear(y) && m === 1 ? 29 : daysInMonth[m];
// incMonth :: Date -> Date
const incMonth = d => {
let dd = new Date(d.getTime());
let day = dd.getDate();
let month = dd.getMonth() + 1;
dd.setDate(5); // should avoid edge-case shenanigans
dd.setMonth(month);
let year = dd.getFullYear();
if (isLastDay(day, month, year)) day = getLastDay(month, year);
dd.setDate(day);
return dd;
};
This was the solution I came up with, which seems small and reliable as far as I can tell. It doesn't need any extra data structures, and relies on setDate(0) to select the last day of the month in the edge cases. Otherwise it leaves the date alone, which is the behaviour I wanted. It also handles wrapping round from one year to the next (in either direction):
function reallySetMonth(dateObj, targetMonth) {
const newDate = new Date(dateObj.setMonth(targetMonth))
if (newDate.getMonth() !== ((targetMonth % 12) + 12) % 12) { // Get the target month modulo 12 (see https://stackoverflow.com/a/4467559/1454454 for details about modulo in Javascript)
newDate.setDate(0)
}
return newDate
}
Note I've only tested this with targetMonth being either one higher or lower than the current month, since I'm using it with 'next' / 'back' buttons. It would need testing further user with arbitrary months.
In an order page I want to implement a calendar, in which, if the user is ordering on friday after 10am, then block the following saturday and sunday in delivery date calendar. Here is a sample code I am trying, but not working as intended.
beforeShowDay: function(date) {
var day = dt.getDay();
var hour = dt.getHours();
if (day == 4) {
// i think, here i want to put the code to disable days
}
}
If I use something like this
beforeShowDay: function(date) {
var day = date.getDay();
var dt = new Date();
var hour = dt.getHours();
return [(day != 5 && day != 6)];
}
I am able to disable Sat and Sun days, but this will disable all the Sat and Sun days. I wnat to disable only the very next Sat n Sun days to be disabled. Also I can get current Hour in var hour, So where should I use the condition to check if the hour is greater than 10am, I am using something like this but not working
beforeShowDay: function(date) {
var dt = new Date();
var hour = dt.getHours();
var day = date.getDay();
if (day == 4 && hour >= 10) {
return [(day != 5 && day != 6)];
}
}
Inside the beforeShowDay function, check the current date to see if it is a Friday and after 10am. If this is true then you also need to check if the date passed as argument is the next Saturday or Sunday:
$(function() {
$("#datepicker").datepicker({
beforeShowDay: function(date) {
// date (Friday March 13 2015 10:00 AM) is hardcoded for testing
var now = new Date(2015, 3 - 1, 13, 10, 0, 0, 0);
if (now.getDay() === 5 && now.getHours() >= 10) {
var now_plus_1 = new Date(now.getTime()); now_plus_1.setHours(0, 0, 0, 0); now_plus_1.setDate(now_plus_1.getDate() + 1);
var now_plus_2 = new Date(now.getTime()); now_plus_2.setHours(0, 0, 0, 0); now_plus_2.setDate(now_plus_2.getDate() + 2);
return [date.getTime() !== now_plus_1.getTime() && date.getTime() !== now_plus_2.getTime(), ""];
}
return [true, ""];
}
});
});
#import url("//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/ui-darkness/jquery-ui.min.css");
body { font-size: smaller; }
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<input id="datepicker">
$('#datepicker').datepicker({
beforeShowDay: function(date){
var dt = new Date(),
day = dt.getDay(),
hour = dt.getHours(),
twoDaysFrmNow = new Date().setDate(dt.getDate() + 2);
return [!(day == 5 && hour >= 10 && date <= twoDaysFrmNow && date > dt)];
}
});
beforeShowDayType: Function( Date date )
Default: null
A function that takes a date as a parameter and must return an array
with:
[0]: true/false indicating whether or not this date is selectable [1]:
a CSS class name to add to the date's cell or "" for the default
presentation [2]: an optional popup tooltip for this date
The function is called for each day in the datepicker before it is
displayed.
beforeShowDay: function(date) {
var day = dt.getDay();
var hour = dt.getHours();
if( day == 4) {
// this is an example of how to use
//first parameter is disable or not this date
//second parameter is the class you want to add ( jquery will remove the click listener, but you probebly want to style it like this date is not available
//third optional tootltip like 'closed on weekends'
return [false,'disabled','weekend']
}
}
I'm trying to test to make sure a date is valid in the sense that if someone enters 2/30/2011 then it should be wrong.
How can I do this with any date?
One simple way to validate a date string is to convert to a date object and test that, e.g.
// Expect input as d/m/y
function isValidDate(s) {
var bits = s.split('/');
var d = new Date(bits[2], bits[1] - 1, bits[0]);
return d && (d.getMonth() + 1) == bits[1];
}
['0/10/2017','29/2/2016','01/02'].forEach(function(s) {
console.log(s + ' : ' + isValidDate(s))
})
When testing a Date this way, only the month needs to be tested since if the date is out of range, the month will change. Same if the month is out of range. Any year is valid.
You can also test the bits of the date string:
function isValidDate2(s) {
var bits = s.split('/');
var y = bits[2],
m = bits[1],
d = bits[0];
// Assume not leap year by default (note zero index for Jan)
var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// If evenly divisible by 4 and not evenly divisible by 100,
// or is evenly divisible by 400, then a leap year
if ((!(y % 4) && y % 100) || !(y % 400)) {
daysInMonth[1] = 29;
}
return !(/\D/.test(String(d))) && d > 0 && d <= daysInMonth[--m]
}
['0/10/2017','29/2/2016','01/02'].forEach(function(s) {
console.log(s + ' : ' + isValidDate2(s))
})
Does first function isValidDate(s) proposed by RobG will work for input string '1/2/'?
I think NOT, because the YEAR is not validated ;(
My proposition is to use improved version of this function:
//input in ISO format: yyyy-MM-dd
function DatePicker_IsValidDate(input) {
var bits = input.split('-');
var d = new Date(bits[0], bits[1] - 1, bits[2]);
return d.getFullYear() == bits[0] && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[2]);
}
I recommend to use moment.js. Only providing date to moment will validate it, no need to pass the dateFormat.
var date = moment("2016-10-19");
And then date.isValid() gives desired result.
Se post HERE
This solution does not address obvious date validations such as making sure date parts are integers or that date parts comply with obvious validation checks such as the day being greater than 0 and less than 32. This solution assumes that you already have all three date parts (year, month, day) and that each already passes obvious validations. Given these assumptions this method should work for simply checking if the date exists.
For example February 29, 2009 is not a real date but February 29, 2008 is. When you create a new Date object such as February 29, 2009 look what happens (Remember that months start at zero in JavaScript):
console.log(new Date(2009, 1, 29));
The above line outputs: Sun Mar 01 2009 00:00:00 GMT-0800 (PST)
Notice how the date simply gets rolled to the first day of the next month. Assuming you have the other, obvious validations in place, this information can be used to determine if a date is real with the following function (This function allows for non-zero based months for a more convenient input):
var isActualDate = function (month, day, year) {
var tempDate = new Date(year, --month, day);
return month === tempDate.getMonth();
};
This isn't a complete solution and doesn't take i18n into account but it could be made more robust.
var isDate_ = function(input) {
var status = false;
if (!input || input.length <= 0) {
status = false;
} else {
var result = new Date(input);
if (result == 'Invalid Date') {
status = false;
} else {
status = true;
}
}
return status;
}
this function returns bool value of whether the input given is a valid date or not. ex:
if(isDate_(var_date)) {
// statements if the date is valid
} else {
// statements if not valid
}
I just do a remake of RobG solution
var daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
var isLeap = new Date(theYear,1,29).getDate() == 29;
if (isLeap) {
daysInMonth[1] = 29;
}
return theDay <= daysInMonth[--theMonth]
This is ES6 (with let declaration).
function checkExistingDate(year, month, day){ // year, month and day should be numbers
// months are intended from 1 to 12
let months31 = [1,3,5,7,8,10,12]; // months with 31 days
let months30 = [4,6,9,11]; // months with 30 days
let months28 = [2]; // the only month with 28 days (29 if year isLeap)
let isLeap = ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
let valid = (months31.indexOf(month)!==-1 && day <= 31) || (months30.indexOf(month)!==-1 && day <= 30) || (months28.indexOf(month)!==-1 && day <= 28) || (months28.indexOf(month)!==-1 && day <= 29 && isLeap);
return valid; // it returns true or false
}
In this case I've intended months from 1 to 12. If you prefer or use the 0-11 based model, you can just change the arrays with:
let months31 = [0,2,4,6,7,9,11];
let months30 = [3,5,8,10];
let months28 = [1];
If your date is in form dd/mm/yyyy than you can take off day, month and year function parameters, and do this to retrieve them:
let arrayWithDayMonthYear = myDateInString.split('/');
let year = parseInt(arrayWithDayMonthYear[2]);
let month = parseInt(arrayWithDayMonthYear[1]);
let day = parseInt(arrayWithDayMonthYear[0]);
My function returns true if is a valid date otherwise returns false :D
function isDate (day, month, year){
if(day == 0 ){
return false;
}
switch(month){
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
if(day > 31)
return false;
return true;
case 2:
if (year % 4 == 0)
if(day > 29){
return false;
}
else{
return true;
}
if(day > 28){
return false;
}
return true;
case 4: case 6: case 9: case 11:
if(day > 30){
return false;
}
return true;
default:
return false;
}
}
console.log(isDate(30, 5, 2017));
console.log(isDate(29, 2, 2016));
console.log(isDate(29, 2, 2015));
It's unfortunate that it seems JavaScript has no simple way to validate a date string to these days. This is the simplest way I can think of to parse dates in the format "m/d/yyyy" in modern browsers (that's why it doesn't specify the radix to parseInt, since it should be 10 since ES5):
const dateValidationRegex = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
function isValidDate(strDate) {
if (!dateValidationRegex.test(strDate)) return false;
const [m, d, y] = strDate.split('/').map(n => parseInt(n));
return m === new Date(y, m - 1, d).getMonth() + 1;
}
['10/30/2000abc', '10/30/2000', '1/1/1900', '02/30/2000', '1/1/1/4'].forEach(d => {
console.log(d, isValidDate(d));
});
Hi Please find the answer below.this is done by validating the date newly created
var year=2019;
var month=2;
var date=31;
var d = new Date(year, month - 1, date);
if (d.getFullYear() != year
|| d.getMonth() != (month - 1)
|| d.getDate() != date) {
alert("invalid date");
return false;
}
function isValidDate(year, month, day) {
var d = new Date(year, month - 1, day, 0, 0, 0, 0);
return (!isNaN(d) && (d.getDate() == day && d.getMonth() + 1 == month && d.getYear() == year));
}