Date range within a conditional statement

I have encountered this code snippet:

function auto_select_param_call_time() {
    if (today() == date("02.01.2017") || today() == date("03.01.2017")) {
        auto_click_param("call_time", "Non-working day");
    } else {
        //Do something else
    }
}

It is designed to check for holidays on specific dates. Now, with approximately 8 new holidays to include in the 'If' condition, listing them individually like "today() == date("02.01.2017")" would quickly become cumbersome.

Is there a more efficient way to specify a range of dates? For instance, can I say "if it falls between 06.05.2017 and 9.05.2017..." without resorting to a switch statement?

Are there any alternative approaches?

Answer №1

It is important to check for holidays in the code.

The code does not mention checking for holidays explicitly. In my area, "02.01.2017" is considered a public holiday as it falls after New Year's Day on a Sunday. However, "03.01.2017" is not recognized as a holiday.

One way to approach this is by creating an array of specific holiday dates and checking if the given date matches any of them, like so:

// Function to format dates in local ISO 8601 format
if (!Date.prototype.toISODateLocal) {
  Date.prototype.toISODateLocal = function() {
    return this.getFullYear() + '-'  +
      ('0' + (this.getMonth()+1)).slice(-2) + '-' +
      ('0' + this.getDate()).slice(-2);  
  };
}

/* Check if a date is a holiday
** @param {Date} date - date to be checked
** @returns {Boolean} true if it is a holiday, 
** otherwise false
*/
function isHoliday(date) {
  var dateString = date.toISODateLocal();
  var holidays = ['2017-01-02','2017-04-14','2017-04-17'];
  return holidays.indexOf(dateString) > -1;
}

[new Date(2017,0,2),
 new Date(2017,3,14),
 new Date()].forEach(function(date) {
   console.log(date.toISODateLocal() + ' is ' +
     (isHoliday(date)? '':'not ') + 'a holiday.');
});
     

Instead of using a range object for contiguous holidays, it is simpler to use an array of individual holiday dates since most holidays are single days. This method works well since there are usually only a few holidays per year.

If you need to determine if a particular date falls between two other dates, you can utilize the comparison operators < and >, as demonstrated below:

// Check if date falls within 1 Jan and 10 Jan inclusive
var rangeStart = new Date(2017,0,1);  // Start date (01 Jan)
var rangeEnd = new Date(2017,0,10,23,59,59,999); // End date (10 Jan)

[new Date(2017,0,5),  //  5 Jan
 new Date(2017,0,10), // 10 Jan
 new Date(2017,0,11)  // 11 Jan
].forEach(function(date) {
  console.log(date + ' in range? ' + (date >= rangeStart && date <= rangeEnd));
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Handling errors in chained promises and routes in Node.js/ExpressJS

I'm currently dealing with some confusion regarding how to handle errors when making function calls. To demonstrate this, I'll be using sequelizeJS as an example. Usually: First.Ctrl var second_ctrl = require( '../ctrl/second'); testC ...

Communication between the content script and background page in a chrome extension is not functioning correctly as intended

Displayed below is the code I posted: manifest.json { "manifest_version": 2, "name": "Demo", "description": "all_frames test", "version": "1.0", "background": { "scripts": ["background.js"] }, "content_scripts": [{ "matches": ...

How do I create a clean HTML file when using the email editor with TinyMCE?

I was able to develop my own email editor, inspired by this particular example. To enhance user experience, I included a download button at the end of the file so that users can easily retrieve their edited content. The issue I'm facing is that tinym ...

Implementing clickable actions to add new entries in a React.js application (using Redux toolkit)

I am currently working on my PET project using Redux toolkit and encountering some issues with inputs. When I add an input on click, it gets added correctly, but I am unsure if it is being added in the right place (it should be added in the ITEMS array). A ...

What is the best way to connect input values with ngFor and ngModel?

I am facing an issue with binding input values to a component in Angular. I have used ngFor on multiple inputs, but the input fields are not showing up, so I am unable to push the data to subQuestionsAnswertext. Here is the code snippet from app.component ...

Please ensure that the menu is included within the HTML file

How can I include a menu from menu.html into index.html? The content of menu.html is: <li><a href="home.html">Home</a></li> <li><a href="news.html">News</a></li> In index.html, the code is: <!docty ...

I'm having trouble getting my accordion menu to work properly. Whenever I click on the question title, the answer doesn't seem to show up or collapse. What could be causing this issue?

I am currently working on a project to create an accordion menu where the answers are hidden and only revealed upon clicking the question. However, when I test it out, nothing happens when I click on the question. Here is my code: .accordion-Section ...

Why is 'this.contains' not recognized as a function when I invoke it within another function?

While attempting to create a Graph and incorporating one method at a time, I encountered an issue. Specifically, after calling a.contains("cats"), I received the error '//TypeError: Cannot read property 'length' of undefined'. Could thi ...

AngularJS Object Comparison: A Comprehensive Guide

My form initiates a GET request to the server upon loading, receiving data that is stored in 'master' and then copied to 'local' as shown below. $scope.dirty = false; init(data); function init(data) { $scope.master = angular.copy ...

Is there a way to verify if a given date falls within a specific range of dates in MongoDB?

{ "_id": { "$oid": "qwerty123" }, "Categories": [{ "mainmodels": [{ "submodels": [{ "price": "1500", "submodelname": "galaxyx21", }, { "price": "1700", "submodelname": "galaxys341", ...

Just starting out with React and encountering the error: Invalid element type, a string was expected

I seem to be going in circles with the following issue as I try to load the basics of a React app into the browser. An error message stating 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite c ...

Deciding whether an altered image has been successfully loaded

Currently, I am stuck on a minor point while creating a small gallery using jQuery. The code snippet looks like this: <script type="text/javascript> $(document).ready(function(){ $('#thumb1').click(function(){ $('#fullimage ...

Display PDF in Forge Viewer using PDF Extension - warning generated by pdf.worker.js

Whenever we attempt to display a PDF file using our own API, the pdf.worker.js generates a warning message and the PDF always appears completely white. https://i.stack.imgur.com/IqGML.png All I can see is this (it's a wide PDF that renders fine in t ...

Tips for ensuring the validity of data in an AJAX request

When trying to fetch data using the REST method, I utilize an AJAX call. While my work is completed, I encounter an issue with validating the "data" within the AJAX call. How can I accomplish this? If there is no data returned from the specified URL, it ...

Is it possible to verify the versions of node and npm prior to running an npm install command?

To ensure only specific versions of node and npm are used before a user can run the npm install command on my module, I need to set certain criteria. According to NPM documentation, I can use the engine attribute for this purpose: "engines": { "nod ...

Leveraging Ajax with PlayFramework Results

As stated in the PlayFramework Document 2.0 and PlayFramework Document 2.1, it is known that Play can return various responses such as: Ok() badRequest() created() status() forbidden() internalServerError() TODO However, when trying to send a response wi ...

Embed a function within a string literal and pass it to another component

Is there a way to pass a function defined in actions to an element? Reducer case 'UPDATE_HEADER': return Object.assign({}, state, { headerChildren: state.headerChildren.concat([action.child]) }); Action.js export const deleteH ...

PhpStorm IDE does not recognize Cypress custom commands, although they function properly in the test runner

Utilizing JavaScript files within our Cypress testing is a common practice. Within the commands.js file, I have developed a custom command: Cypress.Commands.add('selectDropdown', (dropdown) => { cy.get('#' + dropdown).click(); } ...

The 'canvas' module could not be located in the system.Here are the required stacks:- /var/task/index.js- /var/runtime/index.mjs

I am currently developing a lambda function using the serverless framework. The function utilizes chartjs-node-canvas to create graphics, and everything runs smoothly on my MacBook when tested locally. However, when I deploy the function to AWS either dire ...

Using Selenium to handle asynchronous JavaScript requests

Having recently started working with Selenium and JavaScript callback functions, I've encountered a problem that I can't seem to solve on my own. My issue revolves around needing to retrieve a specific variable using JavaScript. When I manually i ...