What methods can be used to retrieve the public holidays for every year with Laravel and JavaScript?

As a newcomer to web programming, I am currently working on calculating the number of days between two dates while excluding weekends and public holidays specific to our country for each year.

I am looking to create a function that allows me to input a year, such as 2021 or 2022, and receive a list of all the public holidays for that year. Additionally, I have already used JavaScript to calculate the date difference while excluding weekends.

The code snippet below showcases the calculation of the date difference excluding weekends:

function getBusinessDateCount (startDate, endDate) {
   var elapsed, daysBeforeFirstSaturday, daysAfterLastSunday; 
   var ifThen = function (a, b, c) { 
       return a == b ? c : a;
    };

elapsed = endDate - startDate; elapsed /= 86400000;

daysBeforeFirstSunday = (7 - startDate.getDay()) % 7; daysAfterLastSunday = endDate.getDay();

elapsed -= (daysBeforeFirstSunday + daysAfterLastSunday);

elapsed = (elapsed / 7) * 5; 

elapsed += ifThen(daysBeforeFirstSunday - 1, -1, 0) + ifThen(daysAfterLastSunday, 6, 5);

return Math.ceil(elapsed); }

   $(document).ready(function(){    
      $(document).on('change','#date2',function (evt) { 
         let start = document.querySelector('#date1').value, 
         end = document.querySelector('#date2').value,
         result = getBusinessDateCount(new Date(start), 
         new Date(end));  
         document.getElementById("days").value = result+ " Days";

    }); });

Currently, I am facing challenges in incorporating public holidays into this calculation to determine the number of days between two dates while excluding both weekends and public holidays specific to our country.

If you have any suggestions or ideas on how to achieve this, please lend a helping hand.

Answer №1

You have two specific dates: date1 from year1 and date2 from year2.

year2 must be greater than or equal to year1

While it's possible that some holidays are not observed every year or were introduced between your specified dates, for simplicity, let's assume that all holidays are celebrated annually.

Given that there are n holidays celebrated each year:

For all years where year1 < y < year2

there will be n holidays. Therefore:

let holidays = 0;
if (year2 > year1 + 2) {
    holidays = (year2 - year1 - 1) * n;
}

Next, you'll need to iterate through the holidays list and compare their months and dates with those of date1 and date2. If a holiday falls after date1, count it once; if it falls before date2, count it again (count twice if both conditions apply):

let month1 = date1.getMonth();
let day1 = date1.getDate();
let month2 = date2.getMonth();
let day2 = date2.getDate();
for (let holiday of holidayArray) {
    let m = holiday.getMonth();
    let d = holiday.getDate();
    if ((month1 < m) || ((month1 === m) && (day1 <= d))) {
        holidays++;
    }
    if ((month2 > m) || ((month2 === m) && (day2 >= d))) {
        holidays++;
    }
}

Now, let's address weekends. Fortunately, this issue has been resolved on Stack Overflow at How to determine number Saturdays and Sundays comes between two dates in java script

function countWeekendDays( d0, d1 )
{
  var ndays = 1 + Math.round((d1.getTime()-d0.getTime())/(24*3600*1000));
  var nsaturdays = Math.floor( (d0.getDay()+ndays) / 7 );
  return 2*nsaturdays + (d0.getDay()==0) - (d1.getDay()==6);
}

Add the result of countWeekendDays to holidays to solve the problem.

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

Can ExpressJs be combined with HapiJs in a NodeJS application?

I'm currently working with an older application that is built using the HapiJs Framework. I am curious if it would be possible for me to incorporate Express for routing while still utilizing HapiJs moving forward? ...

Comprehending the Syntax of the ExtJS Framework

I have recently inherited a project utilizing Sencha's ExtJS framework without any handover or documentation. As I navigate through the code, I find myself trying to decipher certain syntax and exploring resources tailored for newcomers to this specif ...

Issue with Laravel JWT returning token but showing "Unauthenticated" on subsequent request

Every time I log in, I receive my jwt token. However, when I attempt to use that token for other requests on different routes connected with the auth:api middleware, it keeps showing unauthenticated, preventing me from making any further requests. Can som ...

Update the button functionality according to the button's unique identifier

I am trying to dynamically change the button's redirect link based on its ID in my NEXT.JS project, but as a newcomer to this framework, I am unsure of how to accomplish it. I understand that this modification should be done after rendering, possibly ...

Node scripts and node bins are causing errors in Vue.js when running npm

While attempting to run my Vue project with the command npm run serve I encountered an error message that read: [email protected] serve /home/numan/Desktop/vue-getting-started/07-accessing-data/begin/vue-heroes vue-cli-service serve sh: 1: vue- ...

Securing Your Vue.js Application Against Copy and Paste Issues

For the purpose of making it challenging for those who steal content, I want to prevent the copy-paste function on rendered texts within vue.js components. Take a look at this template example: <template> <div id="my-precious-content"> ...

Utilize AngularJS to import a unique custom css stylesheet for every individual webpage

Is there a way to apply different stylesheets to each page without mixing classes? For example, how can I link style.css to index.html and about.css to about.html? This is my AngularJS code: // Define module var myApp = angular.module('myApp', ...

The functionality of sorting or searching in jqGrid does not support columns that utilize json dot notation

Here is the jqGrid code snippet that I am working with: $("#report").jqGrid( { url: '/py/db?coll=report', datatype: 'json', height: 250, colNames: ['ACN', 'Status', &ap ...

Navigating through React Native - A guide to accessing the initial navigation state on React Navigation

Is it possible to retrieve the initial state in a similar format as what is provided by the onStateChange prop in NavigationContainer? Unfortunately, onStateChange does not run during the initial render. While I was successful in obtaining the state whil ...

Can a new class be created by inheriting from an existing class while also adding a decorator to each field within the class?

In the following code snippet, I am showcasing a class that needs validation. My goal is to create a new class where each field has the @IsOptional() decorator applied. export class CreateCompanyDto { @Length(2, 150) name: string; @IsOptional( ...

Converting HTML to PDF: Transform your web content into

I have a couple of tasks that need to be completed: Firstly, I need to create a functionality where clicking a button will convert an HTML5 page into a .PDF file. Secondly, I am looking to generate another page with a table (Grid) containing data. The gr ...

Sequelize: Establishing association upon saving without the need to retrieve another object

Suppose I have two tables, parent and child, where the parent has multiple children. They are properly mapped in Sequelize. Now, I need to add a new child to an existing parent. However, I do not have access to the parent instance, only its id. I am aw ...

How can I retrieve JSON keys and values in JQuery and append them to a list (ul)?

Can you please review this jsFiddle link: http://jsfiddle.net/xY7tx/3108/ Whenever I use getJSON in the provided example, why does the fail part always get executed? I am seeking assistance on how to extract the key and value from the JSON file using jQu ...

Poor performance of ParticleSystems in Three.js on weaker graphics cards

Currently, I am experimenting with particle systems to enhance the rendering speed of a star system, but I have encountered an issue with poor display quality on graphics cards with low capabilities, such as Intel HD which is quite common. The particles th ...

Storing a div in Javascript/HTML and concealing its descendants for later use

I have a div that I can select var selectedCell = null; $(".selectableBox").on('click', function (event) { selectedCell = $(this); } Later on, I need to hide one of the children inside selectableCell called selectableCe ...

What method do you use to determine the duration in weeks?

Initially, my x corresponds to the 10th week of the year 2015 while y represents the 20th week of the same year. x<-as.Date("201510", "%Y%U") y<-as.Date("201520", "%Y%U") The goal is to calculate the difference in weeks between x and y. In this ca ...

Tips for designing a personalized vertical YAxis label in Recharts that will dynamically adjust to accommodate lengthy text

I'm currently working on creating a few composite charts using the Recharts library, and I've encountered an issue where some of the vertical labels on the YAxis are too long and getting cut off. Here's a picture showing the cut-off labels ...

Executing XSS Reflected Attack by Loading an External JS Script via POST Parameter

Experimenting with XSS attacks on my vbox machines, just for kicks! I have two .html files - one works and the other doesn't. The file that works contains: <html> <head></head> <body> <form method="post" action=&q ...

Ensure that the form is submitted only after confirming it in the modal with react-hook-form

**I am facing an issue with submitting react-hook-form on confirm in a modal component. Whenever the user selects confirm, I need the form to be submitted directly. I have tried writing the modal inside FormSubmitButton. Also, I have tried placing it insi ...

Issue with AngularJS Directive: Encountering an error stating "Unexpected token"

Currently working with version 1.20 rc2 and attempting to incorporate a directive: var directives = angular.module('directives', ['controllers']); directives.directive("drink", function() { return { template: '<div>{{f ...