JavaScript Date() constructor failing to capture the correct day

Currently, I am in the process of developing an API that allows users to request transactions based on a specific year and month. This is how the API is structured:

routes.get('/transactions/:member_id/:year/:month', (req, res) => {
    let {member_id, year, month} = req.params;
    let start_date = new Date(year, month - 1, 1);
    let end_date = moment(start_date).add(1, 'months');

    console.log({start_date, end_date});
    res.send({start_date, end_date})
});

To create this API, I am utilizing ExpressJS for the building process and momentjs for date manipulation.

When making a request to this API at http://localhost:8080/transactions/m/2017/10, I am asking for transactions belonging to user m, within the year 2017, and during the month 10, which represents October (hence the adjustment of month - 1 in my implementation above).

The output displayed in the console is as follows:

{ start_date: 2017-09-30T11:00:00.000Z,
  end_date: moment("2017-11-01T00:00:00.000") }

There appears to be confusion arising from the fact that the start day of the month has been set as 1 in the code snippet:

let start_date = new Date(year, month - 1, 1);  

This raises the question of why it is not initiated as 30 instead. What could possibly be going wrong here?

Answer №1

One potential issue you may encounter is related to timezones. To address this, consider implementing the following:

const startDate = new Date(year, --month);
startDate.setUTCDate(1);

JavaScript's Date() function is influenced by the client's local timezone. To ensure consistent results, utilize JavaScript's UTC methods to standardize dates based on GMT World Standard Time. For more information, refer to MDN's JavaScript Date Reference.

As an alternative approach, you can also try the following:

const startDate = new Date(Date.UTC(year, --month, 1));

Answer №2

It appears that the issue at hand is related to timezones.

To address this in your Client, you may utilize

Date.prototype.getTimeZoneOffset()
and incorporate it into your date calculation. However, be sure to include additional time parameters in your URL for accuracy.

Ah, time zones; you truly are a fickle mistress.

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 causes TypeScript's ReadonlyArrays to become mutable once they are transpiled to JavaScript?

Currently, I am in the process of learning Typescript by referring to the resources provided in the official documentation. Specifically, while going through the Interfaces section, I came across the following statement: TypeScript includes a special t ...

Utilize try-catch or async-await within useEffect when testing with Jest

I am currently setting up my initial unit tests using JEST. I've installed Jest Fetch Mock but unfortunately, I keep encountering an error stating "The promise rejected with reason FetchError". After doing some research, it seems like I may need to i ...

Ways to customize easypiechart appearance with CSS styling

I am looking to create a circular counter similar to the one shown below. I have tried using easy-pie-chart but I am unsure how to style the circles to look like the example provided. Is there a way to achieve this through CSS? Any recommended resources o ...

Discovering the size of an attribute in an object using Angular

I am working with a JSON object named "programs" that contains an array of key/value pairs. My task is to determine the count of objects within this array that have the key/value pair "status": "Review". In this case, there are 4 objects in total and 2 o ...

Using JQuery to access options dynamically generated within Select elements

I am currently working on Select elements that are dynamically updated with new options at set intervals. My goal is to programmatically access these new options in order to check if a certain value exists within the select element. I attempted to use the ...

The JQuery function fails to execute following a successful Ajax request

I recently ran into an issue with my Ajax call. Here's the code snippet in question: $("#start-upload-btn").click(function(){ $.ajax({ type: "post", url: "", data: { newProjectName: $('#project-name') ...

PHP enables users to look at manual values in columns and MySQL values row by row

I have created a PHP program to organize seating arrangements for an exam hall. The user manually inputs the names of the halls, which should be displayed in columns in a table. The register numbers are fetched from a MySQL database and should be displayed ...

Issues arise with routing when specific route parameters are implemented

After setting a route parameter in my browser URL, I encountered errors with the routing of the public folder (which contains my CSS, JS, etc.). The app's structure is as follows: app | |-- public | └-- css | └-- profile.css | |-- ...

Adjust the class of a div element located close to its ancestor using JavaScript

I'm trying to change the class of the element #sidePanel from .compact to .expanded dynamically in this code snippet: <div id="sidePanel" class="compact"></div> <div id="topbar"> <div id="buttonContainer"> <div ...

How to activate a media query in response to user interaction using JavaScript

My responsive web page has various designs for different screen sizes, implemented using @media queries. I am interested in allowing users to manually adjust the design for smaller or larger screens without actually changing the screen size. Is there a wa ...

Utilizing Restangular to assign multiple parameters to a variable within the scope variable

Currently learning AngularJS and utilizing Restangular to communicate with a Rails server API. Struggling with grasping the concept of assigning form parameters to a variable in order to use it within my function for posting to the Rails API. Below is an ...

Set a class for the element created with document.createElement('img') method

Is there a way to apply the .rotatable class to the image below without using ('src', 'rotate.png')? $(document.createElement('img')).attr('src', 'rotate.png') css: .rotatable { cursor: move; bac ...

Guide to retrieving the previous URL in Angular 2 using Observables

Can someone help me retrieve my previous URL? Below is the code snippet I am working with: prev2() { Promise.resolve(this.router.events.filter(event => event instanceof NavigationEnd)). then(function(v){ console.log('Previous ' ...

Working with regular expressions on fieldsets in JavaScript jQuery

I'm facing an issue with a JavaScript regexp and I could really use some assistance. Currently, I have an ajax query result saved in a variable (in this case, a regexp) and I am trying to only match the content within the fieldset tag. Here is a sni ...

Show Angular if it is in the array

Presently, I have an ng-repeat function to display comments on articles. It is structured like this: <div ng-repeat="comment in comments"> <li class="item" ng-class-even="'even'"> <div class="row"> ...

What is the trick to incorporating nested tabs within tabs?

My tabs are functional and working smoothly. To view the jsfiddle, click here - http://jsfiddle.net/K3WVG/ I am looking for a way to add nested tabs within the existing tabs. I would prefer a CSS/HTML solution, but a JavaScript/jQuery method is also acce ...

Can const variables be reassigned in JavaScript programming?

Can you reassign a const variable in JavaScript? In C++, we can cast variables to and from const. Is there something similar in JavaScript? My question is const a = 1; unconst(a); a = "xyz"; a === "xyz" // true I'm not referring to object prope ...

What methods can be used to get npx to execute a JavaScript cli script on a Windows operating system

The Issue - While my npx scaffolding script runs smoothly on Linux, it encounters difficulties on Windows. I've noticed that many packages run flawlessly on Windows, but the difference in their operations remains elusive to me. Even after consulting A ...

Developing a unique attribute using AngularJS

As a beginner in AngularJS, I am experimenting with creating directives to manipulate the background-color of a <div> based on specific conditions. I aim to write code like this within my view: <div effect-color="#2D2F2A">content here</div& ...

Sent information from an HTML input form to a PHP action file seamlessly without reloading the page

I am trying to implement a process where an HTML input form communicates with a PHP file without refreshing the page. I have used JavaScript for this purpose, but now I am facing an issue where the $_POST[uid] is not retrieving the ID entered by the user, ...