Troubleshooting the problem with JavaScript's week start date

I am encountering an issue with JavaScript when trying to obtain the first day of the week. It seems to be functioning correctly for most cases, but there is a discrepancy when it comes to the first day of the month.

Could there be something that I am overlooking here?

Let's review the following two scenarios:

1) Example: 05/02/2014

<script>
var d = new Date(Date.UTC(2014, 4, 2, 0, 0, 0));
    var day = d.getUTCDay();
    var indate = d.getUTCDate();
    var diff = indate - day + (day == 0 ? -7 : 0); // adjusting for Sunday as first day of the week
    var sunday = new Date(d.setDate(diff));
    document.write('\nday:' + day);
    document.write('\nindate:' + indate);
    document.write('\nsunday:' + sunday);
    document.write('\diff:' + diff);

</script>

Result: day: 5 indate: 2 sunday: Sun Apr 27 2014 17:00:00 GMT-0700 (Pacific Daylight Time) diff: -3

2) Example: 05/01/2014

<script>
var d = new Date(Date.UTC(2014, 4, 1, 0, 0, 0));
    var day = d.getUTCDay();
    var indate = d.getUTCDate();
    var diff = indate - day + (day == 0 ? -7 : 0); // adjusting for Sunday as first day of the week
    var sunday = new Date(d.setDate(diff));
    document.write('\nday:' + day);
    document.write('\nindate:' + indate);
    document.write('\nsunday:' + sunday);
    document.write('\diff:' + diff);

</script>

Result: day: 4 indate: 1 sunday: Fri Mar 28 2014 17:00:00 GMT-0700 (Pacific Daylight Time) diff: -3

Thank you in advance for any assistance provided!

Answer №1

There are a couple of factors at play here:

  1. When using UTC, the date values being utilized correspond to the previous day and evening. For example, on May 1st, it would actually be referencing April 30th.
  2. The setDate method has a unique characteristic - if the argument is negative, it indicates a certain number of days before the last day of the preceding month. In relation to point #1, this results in situations like treating May 1st as the last day of April, which then rewinds back to March 31st before further deducting 3 days, ultimately giving you March 28th.

The key is to first address the issue with time zone adjustment and UTC, followed by tackling the challenge related to transitioning between months.

  1. To resolve the initial problem, opt for using setDateUTC over simply setDate.
  2. Dealing with the second obstacle requires a more intricate approach. One feasible solution involves subtracting milliseconds instead of days.

    new Date(d + diff * 24 * 3600 * 1000) // converting days to hours, then seconds, then milliseconds
    

Answer №2

Here is a helpful code snippet for you:

var d = new Date(Date.UTC(2014, 4, 1, 0, 0, 0));
var day = d.getUTCDay();
var indate = d.getUTCDate();
var diff = indate - day;
if (diff < 0)
    diff = d.getDate() + diff;
var sunday = new Date(d.setDate(diff));
document.write('\nday:' + day);
document.write('\nindate:' + indate);
document.write('\nsunday:' + sunday);
document.write('\diff:' + diff);
document.write('\dateNumber:' + dateNumber);

Answer №3

you can observe the following JavaScript code snippet to calculate dates:

    var d = new Date(Date.UTC(2014, 4, 2, 0, 0, 0));
    var day = d.getUTCDay();
    var indate = d.getUTCDate();
    var diff = indate - day + (day == 0 ? -6:0); // adjust when day is sunday
    var sunday = new Date(d.setDate(diff));
    document.write('\nday:' + day);
    document.write('\nindate:' + indate);
    document.write('\nsunday:' + sunday);
    document.write('\ndiff:' + diff);

    document.write('<br/>');

    var d = new Date(Date.UTC(2014, 4, 1, 0, 0, 0));
    var day = d.getUTCDay();
    var indate = d.getUTCDate();
    var diff = indate - day + (day == 0 ? -6:0); // adjust when day is sunday
    var sunday = new Date(d.setDate(diff));
    document.write('\nday:' + day);
    document.write('\nindate:' + indate);
    document.write('\nsunday:' + sunday);
    document.write('\ndiff:' + diff);

The output from the above code will be displayed as follows:

day:5 indate:2 sunday:Sun Apr 27 2014 05:30:00 GMT+0530 (India Standard Time) diff:-3
day:4 indate:1 sunday:Sun Apr 27 2014 05:30:00 GMT+0530 (India Standard Time) diff:-3

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

Load annotations from a JSON file with Annotator.js

Seeking assistance with incorporating annotations into my website using annotator.js. I have been encountering difficulties getting it up and running successfully. My goal is to display highlighted annotations upon page load, but I keep receiving a JavaSc ...

What are the steps to generating and sharing 'npm create' scripts?

I am looking to develop and release a script on npm that functions similarly to: npm create qwik@latest or yarn create next-app --typescript However, I am unsure where to begin. Despite searching extensively online, I have not been able to find any helpf ...

Display the div if the input field is left blank

Is there a way to display the div element with id="showDiv" only if the input field with id="textfield" is empty? <form action=""> <fieldset> <input type="text" id="textfield" value=""> </fieldset> </form> <div id="sh ...

Problem with locating elements using Selenium xpath

While using selenium and xpath, I encountered a peculiar issue. On a page, there are 25 <a> tags with nested <img/> tags. I am trying to retrieve all these elements using the findElements() method. Interestingly, upon inspecting the page source ...

Unable to output value in console using eventListener

Hey everyone, I'm new to JavaScript and trying to deepen my understanding of it. Currently, I am working on an 8 ball project where I want to display the prediction in the console. However, I keep getting an 'undefined' message. const predi ...

How can I get the class name of the drop destination with react-dnd?

Imagine having this component that serves as a drop target module. import { useDrop } from 'react-dnd'; import './css/DraggableGameSlot.css'; type DraggableGameSlotProps = { className: string, text: string } function Draggable ...

What measures can be taken to keep the rightmost element from moving when hovered over?

While I am generally happy with the layout, there seems to be a slight jump to the left when hovering over the right-most image (you need to click "show images" to view them). Strangely, this issue does not occur with the last row of images. Any suggestion ...

Is there a way to modify the CSS display property upon clicking a link or button?

I have a ul with the id of "menu-list". The display property is set to "none" in my CSS file, but I want it to switch to "flex" when a link is clicked. I am trying to use the click event on the link to change the display prop ...

There seems to be a glitch in the JavaScript to-do list as it is failing to append new

My attempt at creating a to-do list is not working when I try to add a new entry. Any suggestions? Also, I plan to implement a feature that can calculate the percentage of tasks completed by crossing them off the list. <html> <head> <titl ...

How can I ensure the keyboard does not cover the text input in React Native?

I am trying to figure out how to keep the keyboard from covering the text input field and instead have it appear below. Every time I type something, the keyboard obstructs my view of the text box content. Any help in solving this issue would be greatly a ...

Using Vue.js to submit a form in Laravel and redirecting with a flash message

I am facing an issue where I have two components named Index and Create, loaded from separate blade files. The challenge is passing a flash message as a prop between these components due to their file separation. How can I redirect after submitting a form ...

Modify the button's border color upon click action

I am looking to implement a feature where the border of a button changes when clicked once and reverts back when clicked again. This should apply individually to each of the 16 buttons with the same class. Additionally, I want to enable the ability to clic ...

Using Swig template to evaluate a condition

I'm trying to achieve something similar using swig-template. var remId = $(this).attr('remId'); if (remId) { var end = remId.search('_'); var underscore = remId.slice(end, end + 1); var Id = remId.slice(end + 1, remId ...

Is it necessary to call detach() in rangy?

Utilizing the rangy library in my project and reviewing the documentation for detach: "Destroys the range when it is no longer to be used." I am encountering a dilemma as there isn't a suitable location for me to invoke detach in my code for certain ...

What is the best place to keep my JWT token secure?

Currently, I am working on an application using vue.js and vuex that authenticates to a JSON API server through JWT tokens. The challenge I'm facing is determining the best method for storing the JWT token securely. If I choose to store the token in ...

Having trouble with Vue i18n and TypeScript: "The '$t' property is not recognized on the 'VueConstructor' type." Any suggestions on how to resolve this issue?

Within my project, some common functions are stored in separate .ts files. Is there a way to incorporate i18n in these cases? // for i18n import Vue from 'vue' declare module 'vue/types/vue' { interface VueConstructor { $t: an ...

The confirmation dialogue is malfunctioning

Need some assistance with my code. I have a table where data can be deleted, but there's an issue with the dialog box that pops up when trying to delete an item. Even if I press cancel, it still deletes the item. Here is the relevant code snippet: ec ...

What is the best way to send props from page.js to layout.js in the Next.js app directory?

Is there a way to effectively pass props to layouts in Next.js 13? Can we optimize the approach? Here's an example: // layout.js export default Layout({children}) { return ( <> {/* Display different `text` based on the page.js being ...

Issues encountered while optimizing JSON file in a ReactJS program

I'm struggling with utilizing Array.prototype.map() in Javascript Specifically, I'm reformatting a JSON file within my react app, which looks like: { "id": 1, "title": "Manage data in Docker", "description": "How to use v ...

My toggleclass function seems to be malfunctioning

I am encountering a strange issue with my jQuery script. It seems to work initially when I toggle between classes, but then requires an extra click every time I want to repeat the process. The classes switch as expected at first, but subsequent toggles req ...