5

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 now contains a Date object and today 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 :)

Jack NUMBER
  • 446
  • 1
  • 5
  • 22
  • 1
    http://stackoverflow.com/questions/1050720/adding-hours-to-javascript-date-object is smiliar but doesn't provide answer. – Jack NUMBER Oct 24 '15 at 00:22
  • Why not just use the `now` objected you created? – Griffith Oct 24 '15 at 00:24
  • So what is the actual question? What exactly you want to fix? How an objective answer can be given to a question "is it normal" unless one is a psychiatrist? – Oleg Sklyar Oct 24 '15 at 00:28

3 Answers3

5

Is it normal?

Yes

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();
today.setHours(0,0,0,0);

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 perform similarly do not return this value. I presume that the SET_LOCAL_DATE_VALUE function found in chromium's date.js is assigning the value into the first argument.
pcnate
  • 1,694
  • 1
  • 18
  • 34
  • Please don't reference w3schools. There is the [*language specification*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours) as the normative reference and [*MDN*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours) for examples. – RobG Oct 24 '15 at 00:36
  • Thank you. I understand my mistake. – Jack NUMBER Oct 26 '15 at 08:53
3

I had a similar situation and pcnate answer didn't solved my issue...

What I did was:

var today = new Date();
today = new Date(today.setHours(0,0,0,0));
console.log('Date: '+today);
Philip Enc
  • 1,072
  • 15
  • 21
0

You can manipulate dates easily using datejs or momentjs

date.js:

   Date.today().set({ hour : 0 });

moment.js

   moment().set({ "hour": 0, "minute" : 0, "second": 0});
Sagi
  • 8,972
  • 3
  • 33
  • 41