How to Retrieve a Date using Month, Week, and Day Numbers in JavaScript

Could anyone assist me in extracting the date (yyyy-MM-dd) from the following parameters:

  • year : 2021
  • month : 2 (February)
  • week : 1 (1st week of February)
  • day : 1 (Monday)

Any suggestions or ideas would be greatly appreciated!

Thank you! :)

Answer №1

Although it may not be the most elegant solution, I have implemented this and it functions as intended

    //Input Parameters 
    var year = '2021',
    month = '11',
    week = '4',
    day = '5';

    gs.log(getDateForFloatingBusyDay(year, month, week, day));

function getDateForFloatingBusyDay(year, month, week, day) {

    if (month.length < 2) {
        month = '0' + month;
    }

    var arr_date = generateDaysForMonth(year, month);

    //Iterate through generated dates to find a match for the given week number
    for (var x in arr_date) {

        var d = new Date(arr_date[x]);

        //If the week number from input date matches the desired week number, proceed
        if (getWeekOfMonth(d, true) == week) {
            var firstDayOfWeek = formatDateForSnow(arr_date[x]);

            //In SNOW, Monday is represented as 2 since weeks start on Mondays, so we subtract 2
            day = parseInt(day) - 2;
            //Add days based on the remaining days of the week
            var gdt = new GlideDateTime(firstDayOfWeek);
            gdt.addDaysUTC(day);
            return gdt.getDate();

        }
    }


}


//Calculate the week number of a date within a month
function getWeekOfMonth(date, exact) {
    var month = date.getMonth(),
        year = date.getFullYear(),
        firstWeekday = new Date(year, month, 1).getDay() - 1 , //start on monday added -1
        lastDateOfMonth = new Date(year, month + 1, 0).getDate(),
        offsetDate = date.getDate() + firstWeekday - 1,
        index = 1 , // start index at 0 or 1, your choice
        weeksInMonth = index + Math.ceil((lastDateOfMonth + firstWeekday - 7) / 7),
        week = index + Math.floor(offsetDate / 7);
    if (exact || week < 2 + index) return week;
    return week === weeksInMonth ? index + 5 : week;
};


//Generate array of days for a given month 
function generateDaysForMonth(year, month) {
    var arr_days = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'];
    var arr_date = [];
    for (var x in arr_days) {

        arr_date.push([month, arr_days[x], year].join('/'));

    }

    return arr_date;
}


function formatDateForSnow(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2)
        month = '0' + month;
    if (day.length < 2)
        day = '0' + day;

    return [year, month, day].join('-');
}

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

Tips for resolving an issue with mongoose Model.create becoming unresponsive indefinitely

I'm having trouble understanding why my mongoose Model.create operation isn't completing successfully. The same connection is working well with other controller functions. vscode postman I am attempting to create a new document, but my code s ...

Angular update row and save data to an array

When comparing the data of an edited row with the row just below it, I encounter a specific scenario. In a table containing 5 rows, as I edit records from top to bottom using the provided code snippet, I am able to store the values in an array. The most re ...

Generate a dynamic animation by combining two images using jQuery

My attempt to animate two images is not working. I received some help on Stack Overflow but still facing issues with my CSS and HTML code. This is the code I am using: $(document).ready(function() { $(".animar").click(function() { $("#img4" ...

Issue with Vue.js: Nested field array is triggering refresh with inaccurate information

I've been working on a Vue page where I want to have nested field collections, with a parent form and repeatable child forms. Everything seems to be working fine except that when I try to delete one of the child forms, the template starts rendering i ...

Creating DIV's with Equal Heights Using AngularJS ng-repeat

I'm currently facing an issue with aligning two side-by-side divs to the same height when the content is generated using an ng-repeat function. Using flexbox is causing responsiveness issues, and I'm unsure of the appropriate time to call a jQuer ...

Implementing Material UI datetime-local feature with no minute selection

Is there a way to hide minutes in a TextField with type = datetime-local? <TextField label="From" type="datetime-local" InputLabelProps={{ shrink: true, }} /> This is how it appears on my end: screenshot ...

What is the suitable condition necessary for optimal functionality?

Greetings all! I am a newbie in the world of development and also new to Stack Overflow. This is my maiden post seeking assistance on the following issue: $(document).ready(function() { $(".header").click(function() { if ($(".header-content"). ...

What could be causing the Jquery keydown event to only trigger every other key press?

Recently, I have put together a thumbnail gallery that can be navigated using left and right arrows. I have noticed that while the right arrow works smoothly, the left arrow only seems to navigate to the previous thumbnail every other time. Can someone ple ...

Is the value being used as the key for the array of objects?

Here is an array of objects: { 'data': [{ value: 1000, year: 1990 }, { value: 1001, year: 1990 }, { value: 1002, year: 1990 }, ...

Populating a two-dimensional array with randomly generated numbers using javascript

Apologies if this has been asked before, but I couldn't find any previous posts on the topic as I'm still fairly new to this site! Lately, I've been exploring game development using HTML5 and JavaScript and have gotten into creating tileset ...

Tips for utilizing a received variable within an ejs document

I am currently attempting to update the content of an HTML element in an EJS file with a variable that I have defined in a JavaScript file. let checkbox = document.querySelector('input[name="plan"]'); checkbox.addEventListener('ch ...

Struggling with jquery's addClass method when trying to apply a class to

Below is a sample tr: <tr> <td><input type="text" class="ingredient required" name="ingredient"></td> <td><input type="number" class="amount required" name="amount" ></td> <td><input type="number" c ...

Implementing the @media rule using Javascript

I'm trying to use JavaScript to add an image dynamically, but I want to remove it when the viewport is 600px or wider. This is my approach so far: var img = document.createElement('img'); // (imagine here all the other fields being defined ...

Is there a way to directly set object parameters when a web page loads using JavaScript?

Is there a way to read params values directly into NPAPi plugin? Here is the current JS and form code: <script> var control = document.getElementById('embed'); </script> <form name="formname"> <input type=button value="In ...

JavaScript animation for sequencing traffic lights

I have been working on completing a task that was assigned to me. (iii) Explain the organization of an array that could manage the traffic light sequence. (iv) Develop a script that utilizes the array outlined in part (iii) to create an animated display ...

Using jQuery, compare the values of two elements and update the class based on the comparison outcome

My objective is to retrieve data from a database, place it into an <li> element, and then highlight the larger of the two values obtained from these HTML <li> elements. I have created a jsfiddle, but I am uncertain about how to use the addCla ...

Effortless Inertia Scrolling Implemented in Next.js

My search for achieving smooth inertia scrolling in next.js has left me unimpressed with the available solutions, as they either lack performance or come with some drawback. This medium article and sandbox demo provided a choppy experience, While this jav ...

Utilizing Material UI Pickers and Formik to efficiently handle Date, Time, and Second components

Currently, I am developing a React application with Formik that requires the utilization of date and time pickers. The app is being constructed using Material-UI and I have been exploring the possibilities provided by Material-UI Pickers at Given my relat ...

The use of set.has in filtering does not produce the desired outcome

I am attempting to use Set.has to filter an array in the following way: const input = [ { nick: 'Some name', x: 19, y: 24, grp: 4, id: '19340' }, { nick: 'Some name', x: 20, y: 27, grp: 11, id: '19343' }, { ...

Issues with HTML structure across various devices

Being a novice in web development, I've been experimenting with creating a modal body. https://i.sstatic.net/Qk5BR.png The code snippet below represents my attempt at structuring the modal body: <div className="row modalRowMargin textStyle" > ...