Do you notice a discrepancy in the number returned by Javascript's Date.getUTCDate() when the time component is set to

Consider the following code snippet:

const d = new Date('2010-10-20');
console.log(d.getUTCDate());

If you run this, the console will output 20.

However, if you modify the code like so:

const d = new Date('2010-10-20');
d.setHours(0, 0, 0, 0);
console.log(d.getUTCDate());

The output will now be 19. Are you surprised by this result? Share your thoughts.

Check out this interactive demo on StackBlitz for more insights: StackBlitz Demo

Another interesting observation is that when you specify all zeroes for the time and then call getUTCDate(), the expected date is logged:

const d3 = new Date('2000-10-20T00:00:00Z');
console.log(`D3: ${d3.getUTCDate()}`);

Answer №1

The reason for this discrepancy is the variation in time zones between your location and UTC. The function getUTCDate() converts the time to Coordinated Universal Time (UTC) before retrieving the date. Give this a try:

const d = Date.UTC(2010, 10, 20, 0,0,0);
console.log(new Date(d).getUTCDate());

Additionally, as mentioned by @jonrsharpe in the comments, the issue lies in calling setHours instead of setUTCHours on the date object.

When you initialize a Date object, it inherits the timezone from your environment. In Node.js, this information is obtained from the TZ environmental variable if set. To determine the difference in minutes between your local time and UTC, you can utilize getTimezoneOffset().

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

Steps to include a tooltip on a button that triggers a modal

I am currently utilizing Bootstrap and jQuery to enhance the functionality of components in my application. I am specifically looking to incorporate tooltips into certain elements. The tooltips are implemented through jQuery within my index.html page: < ...

Using indented, multi-line logging in a NodeJS environment can help to

I'm looking for a way to display objects that have been printed with JSON.stringify() in the console, specifically within the context of a Mocha test suite output. While my tests are running, I want the object log lines to be indented further to the ...

Using PHP functions in an AJAX request

I am currently attempting to execute a php loop upon clicking a radio button. I understand that ajax is necessary for this task, but as a beginner in ajax, I am struggling to achieve the desired result. Presently, I am unable to click the radio button at a ...

What is the method for determining the height of a div element when it is set to 'height=auto'?

I am trying to determine the height of a specific div using Javascript. Here is the script I have written: function getMainDivHeight() { var num = document.getElementById('up_container').style.height; return num; } However, this script ...

Accessing the outer index in a nested loop using Handlebars

Imagine I have the code below: <div> {{#each questions}} <div id="question_{{@index}}"> {{#each this.answers}} <div id="answer_{{howToGetThisIndex}}_{{@index}}"> {{this}} </div> {{/each}} </div> ...

When using express and passport-local, the function `req.isAuthenticated()` will typically return a

I'm seeking some insight into my current situation. I've noticed that whenever I call req.isAuthenticated() in an app.router endpoint, running on port 3001 via the fetch API, it always returns false. It seems like the connect.sid is not being pro ...

Challenges with personalized music player

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <style type="text/CSS"> #custom{ font-family: monospace; font-size: 16px; max-width: 650px; ...

Can someone provide guidance on how to validate a HEX color in Cypress?

As I dive into testing with Cypress, my lack of experience has become apparent. I am trying to test the background-color CSS property on a specific element, but running into an issue - everything is in RGB format behind the scenes, while I need to work wit ...

React - Can you explain the purpose of the callback function in the forceUpdate method?

The React documentation mentions that the forceUpdate method includes a parameter called callback. Does this function in any way resemble the second parameter found in setState, which is executed after setting state? Or does it serve a different purpose? ...

Struggling to properly render JSON data

Having trouble accessing specific elements in a script that merges local JSON files using AJAX? The script works fine in Chrome Console, but you can't reach certain elements like 'object.country'. Any suggestions on how to tackle this issue? ...

Searching for data based on specific keywords in Angular 2, rather than using a wildcard search, can be done by utilizing the key-in

My dropdown contains 100 values, and I am currently able to search for these values based on key input using wild search. However, I would like the dropdown to display values based on the specific alphabet that I enter first. HTML: <div class="col- ...

Executing a scroll down action with Selenium in combination with Node.js and the Chai/Mocha testing framework

Browser: Chrome Looking for ways to scroll up or down using Selenium with Node.js (JavaScript). ...

Exploring the process of acquiring a button using refs in external JavaScript

Having encountered a situation where I have two different javascript files, I came across an issue. The first file contains a finish button that was initialized by using refs. Now, I need to access this button in the second file using refs. The code snipp ...

Sending documents via ExpressJS

I'm currently developing a small application using the latest NodeJS and ExpressJS, but I've encountered an issue with uploading files. My routes are set up like this: app.get('/Share', share.index); app.post('/Share/Process&apos ...

Syncing a line's position with the cursor in Angular using the ChartJs Annotation Plugin

I've been working on creating a crosshair using the annotation plugin, and while I've been able to modify the line's value, it doesn't seem to update on the chart. Here are the details of my chart options : public financialChartOptions ...

"Encountering a hang while using the .save() function and only

Issue with storing data in MongoDB This is only my second attempt at saving data to a database and I am still relatively new to the process. I have a form on my HTML page that sends string data to be saved in a MongoDB database. I successfully connected t ...

Convert JavaScript object into distinct identifier

I have a data object where I'm storing various page settings, structured like this: var filters={ "brands":["brand1","brand2","brand3"], "family":"reds", "palettes":["palette1","palette2","palette3"], "color":"a1b2" }; This object is ...

The practice of following the UpperCamelCase convention post object transformation

I encountered a situation where I have an object that returned the result from an RxJs subscribe method: result: any { message: null role: Object success: true } To better manage this object in TypeScript, I decided to convert it to a type ca ...

Trouble with X-editable: Unable to view values when editing and setting values using J

When using X-editable to modify a form with data, I encounter an issue. Initially, the values are loaded from the database to the HTML, but when users try to edit by clicking on the "Edit" button, all values appear as "Empty" instead of their actual cont ...

Check the validity of a password using Angular's reactive forms

For my password validation using ng Reactive Forms, I have a basic html input field for the password and warning paragraphs outlining the password requirements. <div class="field"> <label class="label">Password</label ...