Finding every instance of a specific day within a month

I am in need of a function that can provide me with all the occurrences of a specific day within the current month. I have the first and last day of the month, as well as the length of the month. While I have come across functions that offer the next occurrence of a day, I am looking for a solution that can display all occurrences. I believe this may involve a loop, and I am currently working on it. Any assistance would be greatly appreciated.

$scope.recurrenceFields.by_year_day=$filter('date')($scope.fields.times.dateStart, 'yyyy');
$scope.recurrenceFields.by_month=$filter('date')($scope.fields.times.dateStart, 'M');
    var correntDay = new Date();
                           var lastDayOfMonth = new Date(correntDay.getFullYear(), correntDay.getMonth()+1, 0);
                           var firstDayOfMonth = new Date(correntDay.getFullYear(), correntDay.getMonth(), 1);
                           function daysInMonth(month,year) {
                                return new Date($filter('date')($scope.fields.times.dateStart, 'yyyy'), $scope.recurrenceFields.by_month, 0).getDate();
                            }

Answer №1

Uncertain about the meaning of "all the occurrences of a specific day within a month," but the function below will provide all instances of a particular day within a month based on the input year, month, and day number.

/* @param {number} year - calendar year
 ** @param {number} month - calendar month: 1-Jan, 2-Feb, etc.
 ** @param {number} dayNumber - day number: 0-Sunday, 1-Monday, etc.
 ** @returns {Array} Dates for all days in month of dayNumber
 */
function getAllDaysInMonth(year, month, dayNumber) {
  var d = new Date(year, --month, 1);
  var dates = [];
  var daysToFirst = (dayNumber + 7 - d.getDay()) % 7;
  var firstOf = new Date(d.setDate(d.getDate() + daysToFirst));

  while (firstOf.getMonth() == month) {
    dates.push(new Date(+firstOf));
    firstOf.setDate(firstOf.getDate() + 7);
  }
  return dates;
}

// Return array of all Thursdays in July 2015
console.log(getAllDaysInMonth(2015, 7, 4));
// [Thu 02 Jul 2015,
//  Thu 09 Jul 2015,
//  Thu 16 Jul 2015,
//  Thu 23 Jul 2015,
//  Thu 30 Jul 2015]

// Get all Tuesdays in February 2000
console.log(getAllDaysInMonth(2000, 2, 2));
// [Tue 01 Feb 2000,
//  Tue 08 Feb 2000,
//  Tue 15 Feb 2000,
//  Tue 22 Feb 2000,
//  Tue 29 Feb 2000]

// Get all Sundays in December 2015
console.log(getAllDaysInMonth(2015, 12, 0));
// [Sun 06 Dec 2015,
//  Sun 13 Dec 2015,
//  Sun 20 Dec 2015,
//  Sun 27 Dec 2015]

Answer №2

Take advantage of this convenient service:

angular.module('myApp.utilities')
    .factory('timeManager', function () {
        return {
            parseTimeIntervals: function (startTimestamp, endTimestamp, interval) {
                if(!angular.isNumber(startTimestamp) || !angular.isNumber(endTimestamp) || !angular.isNumber(interval) || startTimestamp===0 || endTimestamp===0) {
                    return [];
                }
                var intervals = [];
                var currentTime = startTimestamp;
                while (currentTime <= endTimestamp) {
                    intervals.push(currentTime);
                    var currentDate = new Date(currentTime);
                    currentDate.setDate(currentDate.getDate() + interval);
                    currentTime = currentDate.getTime();
                }
                return intervals;
            }
        };
    });

To generate all dates within a specified range, simply use the following service:

timeManager.parseTimeIntervals(startDate, endDate, 1);

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

What is the best way to extract individual words from a string based on a specified list of tokens?

I am currently working with a list of tokens used to create artificial Japanese words, which is represented by the following array: var syllables = ["chi","tsu","shi","ka","ki","ku","ke","ko","ta","te","to","sa","su","se","so","na","ni","nu","ne","no","ha ...

Steps for Integrating Kendo Mobile's "Tap to Load More" Feature in Knockout JS

I have a series of data on one page where I'm currently retrieving data from the past two days using linq. I would like to implement a button that, when clicked, will fetch data for the next 5 days. Below is the code snippet used to retrieve data for ...

Encountered an issue during the setup of a meanjs project with the yo generator

Encountered this issue while attempting to set up a meanjs project using the command yo meanjs WARNING engine [email protected]: desired: {"node":">=0.8 <=0.12 || >=1 <=2"} (current: {"node":"5.4.1","npm":"3.5.3"}) In the beginning, ...

I am looking for a sample code for Tizen that allows scrolling of a <div> element using the bezel

Seeking a functional web application in Tizen that can scroll a div using the rotating bezel mechanism. I have dedicated several hours to getting it to work without success. I keep revisiting the same resources for the past three days: View Link 1 View Li ...

Material UI allows for the creation of numbered lists with ease. This

<List> {instructionList.map((el) => ( <ListItem divider key={el.id}> {el.type === 'number' ? <React.Fragmen ...

Unexpected anomaly with Jquery's after() method

Currently, I am working on the following task: I want to dynamically add a new student to a table of existing students using AJAX when a student is added through my user interface. The process involves sending the UI input fields to the controller, which ...

How can I incorporate a second main app.js file in Node.js to improve the organization and cleanliness of my codebase?

Hello, I am currently using Node.js and the Express framework for my project. All of my server-side code is contained within my app.js file, which has become quite complex with almost 250 lines of code. Now, I need to add authentication functionality to my ...

Pressing the ENTER key does not submit the text box data in Rails/Bootstrap, but clicking the SUBMIT button does

I need assistance with my Rails 4 and Bootstrap 3 project. I have implemented an email address field on my page (localhost:3000) where users can enter their email and click the SUBMIT button to send it to the MongoDB database. However, pressing the ENTER k ...

Transitioning images with jQuery

For my college project website that focuses on selling music, I have implemented a buy button that resembles the one seen on Apple's app store. You can view the images of the button here: View Image 1 View Image 2 I am wondering if anyone is famili ...

The function ng-hide is not successful at concealing the button

I am trying to implement logic where the button is hidden if it pertains to deleting a folder, but shown if it's related to the inbox. However, the code provided below does not seem to be working as expected, as the button always appears. <div cla ...

Encountering issues with JavaScript/ajax if statement functionality

Driving me insane! Dealing with 2 modal forms - one for login and another for registration. Javascript handles client-side validation, followed by an ajax call to either a registration or login php file. The PHP files return 'OK' if successful or ...

Just starting out with JS, curious if it's possible to transform these circles into diamonds instead

My goal is to transform this animated field of blinking circles into rectangles or diamonds, whichever is easier. Link: http://jsfiddle.net/Jksb5/1/ HTML <canvas id="pixie"></canvas> JS var WIDTH; var HEIGHT; var canvas; var con; var g; va ...

Is it possible to generate HTML form fields with fixed positions when using Orbeon forms?

Is there a way in Orbeon forms to position input fields at specific coordinates, relative to a background image? I currently have a paper form that fills an entire page. My goal is to use the scanned image of this form as a background and then overlay inp ...

Arranging Angular Array-like Objects

I am in possession of an item: { "200737212": { "style": { "make": { "id": 200001510, "name": "Jeep", "niceName": "jeep" }, "model": { "id": "Jeep_Cherokee", "name": "Cherokee", "nice ...

Convert the jade file to an HTML file while keeping the original file name

I'm currently attempting to configure Jade in a way that allows me to save my Jade files as HTML files while retaining the same file name. For example, I would like the file views/index.jade to be saved as dist/index.html This should apply to all ad ...

When I attempt to send a PUT request, the req.body object appears to be empty. This issue is occurring even though I have implemented the method override middleware

I am currently facing an issue with updating a form using the put method. To ensure that my form utilizes a PUT request instead of a POST, I have implemented the method override middleware. However, upon checking the req.body through console log, it appear ...

What is the purpose behind jade disregarding line breaks and spaces when rendering code?

Utilizing Jade, I am generating HTML by executing the code var generateCodeBlock = jade.compile('div !{text}', {pretty: true});. My aim is to create the following: <div> var json = { labelA: 'a', labelB: 2 ...

Utilizing Angular for enhanced search functionality by sending multiple query parameters

I'm currently facing an issue with setting up a search functionality for the data obtained from an API. The data is being displayed in an Angular Material table, and I have 8 different inputs that serve as filters. Is there a way to add one or more s ...

I am encountering difficulties while attempting to import Typescript files. Upon compiling them into Javascript, I am faced with errors in the web browser, specifically the issue of "exports is not defined"

When I run TodoAppUI.js:15, I get an error saying "Uncaught ReferenceError: exports is not defined" In all my classes, I use the export keyword. For example: export class mysclass { public constructor(){} } Even though I have the proper syntax for impo ...

What could be causing the nonassign error to occur in the angular-bootstrap tabset?

<tabset class="paygrade-tabs"> <tab ng-repeat="tab in rps.currentPayGrade | orderBy: 'payGrade.code' : true track by $index" ng-click="changeTab(tab)" active="activeTabId === tab.id"> <tab-heading> <span> ...