I need help determining the starting date and ending date of the week based on a given date

I am looking to determine the starting date (Monday) and ending date of a specified date using Javascript. For instance, if my date is 2015-11-20, then the starting date would be 2015-11-16 and the ending date would be 2015-11-21.

Answer №1

If you're looking to streamline the process, consider utilizing moment.js.

With a simple line of code like var start = moment('2015-11-20').startOf('week').format('YYYY-MM-DD');, you can achieve your desired outcome.

Alternatively,

You could also use var end = moment('2015-11-20').endOf('week').format('YYYY-MM-DD'); for similar results.

Answer №2

Perhaps this solution could be of assistance to you

var currentDate = new Date();
var currentDay = currentDate.getDay();

$('#start_date').text("Start date: " + subtractDays(currentDate, currentDay-1));

$('#end_date').text("End date: " + addDays(currentDate, 6-currentDay));


function subtractDays(date, days){
    return new Date(date.getTime() - (days * 24 * 60 * 60 * 1000)).toISOString().substr(0,10);
}

function addDays(date, days){
return new Date(date.getTime() + (days * 24 * 60 * 60 * 1000)).toISOString().substr(0,10);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div id='start_date'></div>
<br>
<div id='end_date'></div>

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

Searching the Google Place API to generate a response for dialogflow

I am currently facing an issue while trying to utilize the Google Place API for retrieving details to display a map (by fetching coordinates) and location information (address) as a response from my chatbot. I have created this code snippet, but encounteri ...

How come CSS styles are not being applied to forms in AngularJS?

When attempting to apply CSS styles to a form in order to indicate invalid input, I encountered an issue. Even after using the important tag, the styles did not change. I created a dynamic form from JSON and now need to validate it. Following a suggestion ...

"Using Node.js Express 4.4 to efficiently upload files and store them in a dynamically

Looking for recommendations on the most efficient method to upload a file in node.js using express 4.4.1 and save it to a dynamically created directory? For example, like this: /uploads/john/image.png, uploads/mike/2.png ...

Adding Vuetify to a Vue web component, then proceed to pass props to enhance its functionality

Currently working on developing a web component with Vue and using vuetify component library. The goal is to export it as a web component, but facing difficulties when trying to pass props to the exported component in the index.html file. Following the ste ...

An easy guide to rerouting a 404 path back to the Home page using Vue Router in Vue.js 3

Hello amazing community! I'm facing a small challenge with Vue.js 3. I am having trouble setting up a redirect for any unknown route to "/" in the router. const routes = [ { path: "/", name: "Home", component: Home, }, { path: "* ...

A malfunction report stemming from an HTTP error code while using react.js/javascript

In my react.js application, I have a Component that displays an error code. It currently looks like this: https://i.stack.imgur.com/2usiy.png Now, in addition to displaying just the code, I also want to show the reason for the error. Similar to how this ...

Is the `visibility: hidden` property not functioning as expected?

I am trying to conceal the script for the photoset until it is fully loaded, but unfortunately the code below does not seem to be effective: JavaScript $('.photoset-grid').photosetGrid({ rel: $('.photoset-grid').attr("data-id"), gutte ...

Generate a progress indicator upon user clicking a hyperlink

I am looking to implement a loading bar that appears when the user clicks a link. Additionally, I need to upload data (via Ajax) into div#work if needed, followed by displaying the loading bar. Once the data is successfully uploaded, I want the script to s ...

What is the process for obtaining a fresh token from Cognito using the frontend?

Currently, I am working with a react app that utilizes Cognito for user authentication. My main query revolves around making a call to Cognito using the refresh token in order to receive a new token. Despite researching various examples provided by Cognit ...

Leaving the pipeline of route-specific middleware in Express/Node.js

My implementation involves a sequence of "route specific middleware" for this particular route: var express = require('express'); var server = express(); var mw1 = function(req, resp, next) { //perform actions if (suc ...

Toggling the form's value to true upon displaying the popup

I have developed an HTML page that handles the creation of new users on my website. Once a user is successfully created, I want to display a pop-up message confirming their creation. Although everything works fine, I had to add the attribute "onsubmit= re ...

Create bubble diagrams to display detailed information within a line graph using Chart.js

After creating a line chart with chartJS, I am looking to enhance it by adding bubbles to indicate specific data points such as the mode, red, and amber levels. While I have successfully drawn the lines on the chart, I am unsure of how to incorporate these ...

Is there a way to merge two separate on click functions into one cohesive function?

I currently have two separate onclick functions as shown below. They are functioning properly but I am considering combining them for optimization purposes. Essentially, clicking on xx displays certain elements, hides others, and adds a class. Clicking o ...

Real-time functionality in React component and Apollo Client is not functioning as expected

I am struggling to develop a user system as it is not working in real-time, causing confusion for me. To illustrate my problem and code, I have set up a sample Sandbox. Please note that this example does not include any validation features and is solely f ...

Incorporating a protected Grafana dashboard into a web application

I am looking to incorporate Grafana into my web application using AngularJS. The main objective is to allow users to access the Grafana UI by clicking on a button within my application. Setting up an apache reverse proxy for Grafana and ensuring proper COR ...

Unusual behavior of .replace() function observed in Chrome browser

<div> <input type="text" class="allownumericwithdecimal"/>saadad </div> $(".allownumericwithdecimal").live("keypress keyup ", function (event) { $(this).val($(this).val().replace(/[^0-9\.]/g, '')); var text = ...

Exploring the benefits of using Styled Components for creating global styles in React and Next.js: Should you opt for a mix of CSS files and Styled Components?

Recently, I implemented Styled Components in my Next.js app by following the guidelines from Styled Components. Currently, I am delving into the realm of best practices for managing global styles with Styled Components. The first aspect that piques my curi ...

Dealing with the challenges posed by middleware such as cookie access and memory leaks

Utilizing express with cookieParser() where my client possesses the cookie named: App.Debug.SourceMaps. I've crafted a middleware as follows: app.get('/embed/*/scripts/bundle-*.js', function(req, res, next) { if (req.cookies['App ...

What is the proper method to set up jQuery in scripts loaded via AJAX? I keep receiving the error message: 'Uncaught TypeError: Object #<Object> has no method'

I have developed a website with an index page that contains a div for loading the content of each individual page. Initially, I included external JS files and performed initializations within each separate page. However, most of the time when the page loa ...

PHP: A guide on validating textboxes with jQuery AJAX

How can I use jQuery AJAX to validate a textbox on focusout? The validation process includes: Sending the value to a PHP page for server-side validation Displaying an alert message based on the validation result I have only impl ...