Why do the first line of code return an object of type "Date" whereas the second one returns a "number" ?
According to the doc (.asp) setHours() should just change the value of the hour of the date object, not convert it.
The code :
var date = new Date();
var date2 =date.setHours(19);
Thanks !
Why do the first line of code return an object of type "Date" whereas the second one returns a "number" ?
According to the doc (http://www.w3schools.com/jsref/jsref_sethours.asp) setHours() should just change the value of the hour of the date object, not convert it.
The code :
var date = new Date();
var date2 =date.setHours(19);
Thanks !
Share Improve this question asked Dec 14, 2016 at 17:20 user5819768user5819768 7 | Show 2 more comments5 Answers
Reset to default 8You need to wrap your answer in new Date()
. Like this:
var date2 = new Date(date.setHours(19));
The setHours() method sets the hours for a specified date according to local time, and returns the number of milliseconds since 1 January 1970 00:00:00 UTC until the time represented by the updated Date instance.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours
According to the doc (
http://www.w3schools.com/jsref/jsref_sethours.asp
) setHours() should just change the value of the hour of the date object, not convert it.
That document says:
Return Value: A Number, representing the number of milliseconds between the date object and midnight January 1 1970
It doesn't convert the date object though. It modifies the existing one and then returns a value.
The date object you created before still exists, with the modified hour value, and any references to it (like the one you still have in the variable named date
) will remain available.
It's quite simple, just read the documentation about it.
See below what that method returns.
Return value
The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date.
I came here because I got a date.getTime is not a function
error from Firebase Cloud Functions.
It is important to remember that setHours()
returns a timestamp (number) AND modifies the date object (date).
For Firebase users who want to use the firebase timestamp and setHours()
method:
// import Timestamp
const { Timestamp } = require('firebase-admin/firestore');
// create a new date object and reset the time to 00:00 (to sort or compare just by days, not by time/hours)
const dateForQuery = new Date();
dateForQuery.setHours(0, 0, 0, 0);
// setHours returns a timestamp, but it also modifies the date object. At this point, dateForQuery is already modified and we don't need to wrap it again in a new Date().
...
dateCreated: Timestamp.fromDate(dateForQuery),
...
date
object... you'll see that it's set as you specified. – Jeff Mercado Commented Dec 14, 2016 at 17:24