Jack NUMBER Jack NUMBER - 1 year ago 87
Javascript Question

setHours() convert my Date object in string timestamp

I try to set a date to midnight to simplify my date manipulation, for this I wrote this part of code:

var now = new Date();
today = now.setHours(0,0,0,0);
console.log(now, today);

I'm surprised to see
contains a Date object and
a timestamp. This brings errors when I want to use getMonth() or other date's functions. It's paintful to recreate a Date object with the timestamp.

Is it normal? How can I fix this?

(Feel free to update my post to correct my bad english :)

Answer Source

Is it normal?


How can I fix this?

You are assigning the return value of now.setHours(0,0,0,0)to today.

Maybe what you are looking for is something like this:

var now = new Date();

var today = new Date();

In this way, setHours is acting upon the value you wish to have the hours set on. This is the primary manner of using setHours.

Other details

  • The specification doesn't appear to mention the return value. Other sites such as w3schools do.
  • The Chromium setHours source shows a value being return though other functions that do similar do not return this value. I presume that the SET_LOCAL_DATE_VALUE function found chromium's date.js is assigning the value into the first argument.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download