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

Python tutorial: Combine the current date with a string such as '1 hour and 5 seconds'

I need to dynamically add a datetime value like '2019-10-18 11:46:08' + '5 hours 5 seconds', where the time duration (e.g. 5 hours 5 seconds) is variable and retrieved from the database. The challenge is that this time duration is not f ...

Scrolling animations tailored to the navbar using jQuery

My fixed header contains a few links, and I've written some code that almost works perfectly. The issue is that there's a delay when the second function is executed. While it successfully scrolls to the top of the page when the linked element is ...

Encountering an unrecognized error on Windows when attempting to execute a child process with regex return

Below is the code I am utilizing to retrieve Make file targets: const command = `make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\\/t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'`; cp.exec(command, options, (error, stdout, s ...

Steps to apply the nav-active class to a navigation using jQuery just once

Seeking assistance with a problem I am facing. I would like to add the nav-active class to an li element only once, meaning if a child element is selected, then the parent li should not have the nav-active class. Below is the code I am using, but it does n ...

experiencing an excessive amount of rerenders when trying to utilize the

When I call the contacts function from the main return, everything seems fine. However, I encounter an error at this point: const showContacts = React.useCallback( (data: UsersQueryHookResult) => { if (data) { return ( < ...

Displaying XML data in an HTML table

Encountered a challenge while fetching data from an external XML document using JS. Following the w3schools tutorial for AJAX XML, but faced an issue I couldn't resolve. The XML structure is as follows: <root> <document-id> <author ...

Set boundaries for the width and height of an image in the input field

Looking to restrict the size of an image in an input field using HTML, CSS, and JavaScript/jQuery. Goal is to maintain a perfect square aspect ratio for profile photo uploads (for example, 200x200 or 300x300). ...

Transition the object in smoothly after the slide has changed

How can I make the h4 tags fade in after the divs slide into view, while also adding the class "current" to each visible slide? Check out the example on JSFiddle here. <div class="slider"> <div class="slides"> <div class="slide ...

Passing data from the server to the HTML page for manipulation

I need assistance in retrieving and manipulating the value stored in the variable $result[] from a PHP file to my HTML file for further processing. Can you provide guidance or reference code on how to return data from server side to client side? Here is a ...

Organizing requests in PHP: What are the best methods?

My attempt to use the code below for queuing requests has not produced the desired results! <?php $Sleep_Time = "10"; if (isset($_POST["String"])){ $File = "Edit_File_Content.txt"; while(file_exists($File . "_L ...

Loading JSON data into HTML elements using jQuery

I am currently grappling with coding a section where I integrate data from a JSON file into my HTML using jQuery. As a newbie to jQuery, I find myself at a standstill. https://jsfiddle.net/to53xxbd/ Here is the snippet of HTML: <ul id="list"> ...

Using Websockets in combination with AngularJS and Asp.net

While working on my application that uses AngularJS with Websocket, I encountered a specific issue. The WebSocket communication with the server works fine as users navigate through different pages in Angular. However, when a user decides to refresh the p ...

Guide to uploading multiple images to an Amazon AWS S3 bucket using Node.js, Angular, and JavaScript

Can anyone share insights on where and how E-commerce websites typically upload their product images? Has anyone had experience using Amazon AWS S3 bucket for this purpose? Additionally, does anyone know how to upload or retrieve multiple images at once ...

Instructions for adding the more-vert icon from material-ui into a react project

I've been searching tirelessly, but I can't seem to locate it. Where exactly is the location of this in material-ui? I've seen others using it. Any assistance would be greatly appreciated. My initial thought was: import MoreVertIcon from & ...

"Using Javascript to assign a class based on a date being greater than

I am facing an issue with a script that applies a CSS class to table cells if the date is greater than a certain value. Currently, the script only works for today's date. I need it to work for dates within and outside of this week as well. $('td ...

Exploring an array in Angular 2 using TypeScript

Just starting out with typescript and angular2 and working through some issues. I have a form that needs to display results from an array of changing items, so I don't know the exact index of each result. Here is my scenario: In my form.html file: ...

Extracting the month and year from a datetime string: A simple guide

I am working with a JSON object that includes a field called Month with a string datetime value- { Month : "31-Jan-2022 12:00 AM (EST)" .... .... } Is there a way to extract the Month Name and Year from this string using JavaScript's dat ...

Having trouble clicking or interacting with JavaScript using Selenium and Python

Issue: Unable to interact with elements on a specific webpage after opening a new tab. Using WebDriver Chrome. I can successfully navigate the initial webpage until I click a link that opens a new tab, at which point I am unable to perform any actions. ...

Measuring the success of Vuejs app

Seeking performance metrics for a Vue application. Interested in metrics for the entire app as well as specific components. I am aware of using Vue.config.performance = true; to enable performance monitoring through dev tools, and I have considered utiliz ...

Trouble arising from PHP's encoded array

I am encountering an issue with retrieving a value from PHP and passing it to Javascript. The PHP array is encoded like this : echo json_encode($myArray); On the Javascript side, I use the following code within the $.ajax method: success:function (data) ...