What is the reason for new Date().setHours(18) providing a numerical value instead of a date object?

Why does the first line of code returning an object of type "Date" while the second one returns a "number"?

Based on information from the documentation (http://www.w3schools.com/jsref/jsref_sethours.asp), setHours() is supposed to only change the hour value of the date object, not convert it.

The following code is being discussed:

  var currentDate = new Date();

  var changedDate = currentDate.setHours(19);

Any insights or explanations would be greatly appreciated!

Answer №1

It is necessary to enclose your response within new Date(). Similar to the following:

let time = new Date(date.setHours(19));

Answer №2

The setHours() function adjusts the hour value of a specified date using the local time zone and then provides the number of milliseconds that have elapsed since January 1, 1970 00:00:00 UTC up to the updated Date instance.

Learn more about the setHours() method here

Answer №3

As noted in the documentation (

http://www.w3schools.com/jsref/jsref_sethours.asp
), setHours() simply updates the hour value of the date object without converting it.

The documentation states:

Return Value: A Number, representing the number of milliseconds between the date object and midnight January 1st, 1970

This method does not actually convert the date object; instead, it modifies the existing object and provides a return value.

The original date object remains unchanged with only the hour value updated. Any references to this object, such as the one stored in the variable named date, will persist.

Answer №4

If you're looking for more information, take a look at the official documentation.

Below, you can find the result of using that specific method.

Result

The return value is the number of milliseconds from 1 January 1970 00:00:00 UTC to the updated date.

Answer №5

I encountered an issue with Firebase Cloud Functions where I received a date.getTime is not a function error.
It's crucial to note that when using the setHours() method, it both returns a timestamp (number) and modifies the date object.

For Firebase users looking to utilize the firebase timestamp along with the setHours() method:

// Import Timestamp
const { Timestamp } = require('firebase-admin/firestore');

// Create a new date object and set the time to 00:00 to focus on days rather than hours for sorting or comparisons
const dateForQuery = new Date();
dateForQuery.setHours(0, 0, 0, 0);

// Although setHours modifies the date object, it also returns a timestamp. Therefore, there's no need to create a new Date() instance.
...
dateCreated: Timestamp.fromDate(dateForQuery),
...

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

Highcharts - problem with chart width being fully rendered

I am currently using a Highcharts column chart and I am looking to make it a fully responsive chart with 100% width. The container for the chart is a simple <div> without any additional formatting. Upon document load, the chart remains at a fixed wid ...

Tips for creating a script that waits for a specific amount of time before moving on to the next execution block in Protractor

Need to automate a test case that involves filling out a form with 5 date pickers and 30 fields. Once the form is filled, a jar needs to be invoked to retrieve the data from the DB and process it independently. Note: The jar does not send any value back t ...

Utilize jQuery to dynamically add or remove elements by referencing specific HTML elements

My goal is to dynamically add an element to a dropdown menu and then remove it after selection. I initially attempted to define the htmlElement reference in this way: (Unfortunately, this approach did not work as expected) var selectAnOption = "<option ...

Automatically populate form fields with data from the clicked row in the HTML table when using JSP

Attempting to populate form fields using jQuery or JavaScript with row elements selected by clicking on the row. Tried a solution from Stack Overflow that didn't work as expected. I'm new to this, so please bear with me. (http://jsbin.com/rotuni/ ...

"Error in react-three-fiber: Only the last mesh retains its model, all others are

Currently, I am working on a React application where I am using react-three-fiber to visualize data in a 3D environment. My goal is to create various models by passing data representing their characteristics as props into components. However, I am encounte ...

Creating customized JavaScript bundles with TypeScript - a beginner's guide

Our ASP.NET MVC application contains a significant amount of JavaScript code. To optimize the amount of unnecessary JS being loaded to the browser, we utilize the BundleConfig.cs file to create multiple bundles. On the View, we implement logic to determin ...

Leverage AJAX on the client-side for optimal performance while utilizing node.js

I am currently working on a simple nodejs application that displays HTML pages. Within this application, there are two buttons that are linked to JavaScript functions in separate files. One of the functions uses ajax, while the other does not. However, I a ...

Overlay Image on Card, Overflowing into Card Body

I currently have a webpage featuring cards. Each card includes a thumbnail at the top with an overlay. The main content of the card needs to be positioned outside of the overlay, but it ends up overflowing onto it. Take a look at the demo: https://codepe ...

Error: Unable to Navigate to Present Location ("/search") as It is Duplicated

I keep encountering the error message NavigationDuplicated when I attempt to perform multiple searches. My search function is located in the navbar, and it's configured to capture the input value using a model. Subsequently, this value is passed as a ...

What is the correct method for iterating through this array of objects and eliminating those with either null or empty item.text values?

Currently, I am working with the following Array: const contactInfo = computed(() => { return [ { id: 'address', icon: 'detail/clubLocation', text: `${props.data.contactInfo.address}` ...

Is utilizing unregistered HTML elements for semantic purposes considered poor practice?

When it comes to styling and semantic purposes, I am considering using unregistered web components. This means utilizing tags like <t-card></t-card> without registering them with customElements.define. Surprisingly, the browser and stylesheets ...

Guide to comparing the contents of two text fields and highlighting the altered characters using ReactJS

Is there a way to compare the contents of two Material-UI textfields and identify the characters that have changed in both? I came across a similar question, but it was specifically for ReactJS rather than C# Windows Forms: How can you highlight the chara ...

Unable to access a value from an object in Node.JS/MongoDB platform

I'm seeking assistance with my NodeJs project. The issue I am facing involves checking the seller's name and setting the newOrder.support to match the seller's support internally. Despite logging the correct value within the findOne() func ...

Launching a web application on Vercel, the back-end has yet to be initialized

I am currently working on a Next.js/TypeScript web application project hosted on Vercel's free tier. To run my project, I use npm run dev in the app folder to start the front end and then navigate to the back-end folder in another terminal and run npm ...

Upon utilizing JSON.parse in Express, an unexpected token < in JSON was encountered at position 0 while attempting a client side fetch POST

I'm trying to send a basic object through a fetch request to my express server, but I keep encountering an error when attempting to log it. Currently, if I log req.body (with the header 'Content-Type': 'application/x-www-form-urlencode ...

Mapping an object in a table only results in the final value being displayed

I am facing an issue with my data object containing an array of data that I have mapped inside a table. The problem arises when I try to retrieve the id value of any item in the table's rows using console.log(). It always returns the id of the last it ...

Connecting the search results page with the specific details page

Currently, I am developing a results page for my website and require assistance with linking each restaurant to a detail.php page. The project involves showcasing all the restaurants in San Francisco along with their health inspection scores, address, and ...

Prevent Console tracing in Angular when encountering errors with $http requests

As I work on my application, I rely on a REST api to fetch my data. When I make a request like this: $http.get('api/entity/' + $scope.entityId).success(/* DO STUFF */).error(/* DO STUFF */) In the service, if the entityId is not found, I return ...

JavaScript: Only a single function call is successful

Recently, I encountered an issue with my registration form. Everything was working smoothly until I attempted to add a new onblur() event to a different text field within the same form. Surprisingly, this caused the original ajax call to stop functioning, ...

save choice in antd select in react js

In the process of developing a ReactJS project, I am utilizing the antd select component to display a list of companies. Upon selecting a company name, the users registered under that company will be shown. The attached video showcases the functionality fo ...