Time function that checks for certain days


Time function that checks for certain days



I have the following time function that I use to output if the business is open or closed. The way I have it coded works fine for normal business weeks. What I am wanting to do is program it for holidays, such as Christmas, 4th of July, etc that are always on the same day, so the output shows we are closed.



How would I program in the fixed holidays?


function timeNow() {

//Get time
var d = new Date(),
h = ('0' + d.getHours()).slice(-2),
m = ('0' + d.getMinutes()).slice(-2);

//Get Day
new Date().getDay();
var day = new Date().getDay();
console.log(day);
var operateDay = '';
if (day >= 1 && day <= 5) {
operateDay = true;
} else if (day < 1 || day > 5) {
operateDay = false;
}

// Checking time range
var operatingTime = ((h >= 8 && h < 17) || (h === 8 && m == 0));
var closedTime = (h >= 17 || h <= 8);
var operateStatus = '';

if ((operatingTime) && (operateDay = true)) {
operateStatus = 'Our office is currently open';
$('#closedWrap').addClass('block');
$('#operationStatus').addClass('open');
} else if (closedTime) {
operateStatus = 'Our office is currently closed';
$('#closedWrap').addClass('block');
$('#operationStatus').addClass('closed');
} else if (operateDay = false) {
operateStatus = 'Our office is currently closed';
$('#closedWrap').addClass('block');
$('#operationStatus').addClass('closed');
}

return operateStatus;
}
var operation = timeNow();
$('#operationStatus').html(operation);





Speaking just conceptually, I would imagine an array of the days to force to be closed, potentially already as Date objects, and then you could perform logic on that array to check and see if the date is the same as any of the array dates. If so, the place is closed.
– Taplar
Jun 29 at 16:03





@Taplar I am not sure how to specify a day.
– Paul
Jun 29 at 16:41





Ex. new Date('07-01-2018') would be July 1st
– Taplar
Jun 29 at 16:45


new Date('07-01-2018')





@Taplar new Date('2018-07-01') might yield better results, and you'd get best results with new Date(2018, 6, 1).
– Mike McCaughan
Jun 29 at 17:06


new Date('2018-07-01')


new Date(2018, 6, 1)





@MikeMcCaughan new Date('2018-07-01') in the console evaluates to Sat Jun 30 2018 which surprised me as I thought Date would expect ISO, but that is why I reversed the order.
– Taplar
Jun 29 at 17:07


new Date('2018-07-01')


Sat Jun 30 2018




1 Answer
1



I've modified your original function and created an initial version, that handles a custom, easily "configurable", human-readable list of specific holidays.




/**
* Returns the office's open/closed state.
*
* @param {Date} [time] - A custom Date object to override the current time.
* @returns {string} The state of the office (open or closed).
*/
function timeNow(time) {
// Holidays - month-day format, it's adjusted for human-readability, so
// January is 1, February is 2 ... December is 12
var holidays = [
'01-01', // New Year's Day
'07-04', // Independence Day,
'11-11', // Veterans Day
'12-25', // Chirstmas
'12-31', // New Year's Eve
];

// Possibility of overriding the current date, if needed
time = time || new Date();

// Get time
var d = time,
h = ('0' + d.getHours()).slice(-2),
m = ('0' + d.getMinutes()).slice(-2);

// Get day
var day = time.getDay();
var operateDay = '';
if (day >= 1 && day <= 5) {
operateDay = true;
} else if (day < 1 || day > 5) {
operateDay = false;
}

// Checking time range
var operatingTime = ((h >= 8 && h < 17) || (h === 8 && m == 0));
var closedTime = (h >= 17 || h <= 8);
var operateStatus = '';

// Check against holidays if the store is seemingly open
// Since in JavaScipt's built-in Date object, January is 0, February is 1 ... December is 11,
// to be humanly usable, add 1 to it, hence the name "adjusted"
var adjustedMonth = time.getMonth() + 1;
var dayOfMonth = time.getDate();

if (operatingTime) {
for (var i = 0, len = holidays.length, holiday, holidayMonth, holidayDay; i < len; i++) {
// Process the specific holiday month-date format
holiday = holidays[i].split('-');
holidayMonth = parseInt(holiday[0], 10);
holidayDay = parseInt(holiday[1], 10);

// Check, whether today is a holiday ...
if (adjustedMonth === holidayMonth && dayOfMonth === holidayDay) {
// ...and if it is, then ...Hooray! Hooray! It's a Holi-Holiday
operatingTime = false;
closedTime = true;
break;
}
}
}

if ((operatingTime) && (operateDay = true)) {
operateStatus = 'Our office is currently open';
$('#closedWrap').addClass('block');
$('#operationStatus').addClass('open');
} else if (closedTime) {
operateStatus = 'Our office is currently closed';
$('#closedWrap').addClass('block');
$('#operationStatus').addClass('closed');
} else if (operateDay = false) {
operateStatus = 'Our office is currently closed';
$('#closedWrap').addClass('block');
$('#operationStatus').addClass('closed');
}

return operateStatus;
}

// Testing
var shouldBeOpen = [
'2018-06-25',
'2018-06-26',
'2018-06-27',
'2018-06-28',
'2018-06-29'
];

var shouldBeClosed = [
'2018-01-01',
'2018-07-04',
'2018-11-11',
'2018-12-25',
'2018-12-31',
'2019-01-01'
];

var STATUS_OPEN = 'Our office is currently open';
var STATUS_CLOSED = 'Our office is currently closed';

// converts a human-readable year-month-day to UTC date
function strToUtcDate(string) {
var parts = string.split('-');
var year = parts[0];
var month = parts[1];
var day = parts[2];
return new Date(Date.UTC(year, month - 1, day, 12, 0, 0));
}

shouldBeOpen.forEach(function (string) {
var date = strToUtcDate(string);
var status = timeNow(date);

if (status === STATUS_OPEN) {
console.log('opened, as it should on:', date);
} else {
console.log('closed, BUT IT SHOULD NOT ON:', date);
}
});

shouldBeClosed.forEach(function (string) {
var date = strToUtcDate(string);
var status = timeNow(date);

if (status === STATUS_CLOSED) {
console.log('closed, as it should on:', date);
} else {
console.log('opened, BUT IT SHOULD NOT ON:', date);
}
});


https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js





Thanks Richard. This definitely helps out a lot. Is there a way that I could test this by changing the date to 7-4 and running it live?
– Paul
Jun 29 at 17:31





You're welcome! Yes, of course, but by live, I hope you mean staged on your server and not in production. Before you want to deploy it in any way, please use my modified source and create a meaningful unit test suite. I'm pretty sure there are egde cases, when it will return a false positive/negative.
– Richard Szakacs
Jun 29 at 17:47






How could I change the date? Because, updated my code with yours, but I think my output it solely just reading my returned function return operateStatus; to populate the output. You can view it here: test.mbkit.com/test.mbkit.com/contact
– Paul
Jun 29 at 17:50


return operateStatus;





Please, use only the timeNow() function I've changed, not the whole sample with the quick-n-dirty tests and all. Change the date on your own computer for starter, but please, write some a proper unit test suite for your own sake.
– Richard Szakacs
Jun 29 at 17:56


timeNow()





Ok, so I just took out the other code except the timeNow() function. How do I manually change the date to reflect 7/4? I am new to the time/date functions.
– Paul
Jun 29 at 17:58






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Export result set on Dbeaver to CSV

Opening a url is failing in Swift