Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Dates : change time

Do you know an elegant way to change the time in a Date Object in javascript

The strangness is those setters that return Number object

var date = new Date().setHours(0,0,0,0);

date is a Number not a date..

so let's say I have a date var date = new Date()

and I want to change time

Thank you

like image 288
mlwacosmos Avatar asked Dec 06 '12 09:12

mlwacosmos


People also ask

Can JavaScript handle dates and time?

The date and time is broken up and printed in a way that we can understand as humans. JavaScript, however, understands the date based on a timestamp derived from Unix time, which is a value consisting of the number of milliseconds that have passed since midnight on January 1st, 1970.

Does JavaScript Date have timezone?

JavaScript's internal representation uses the “universal” UTC time but by the time the date/time is displayed, it has probably been localized per the timezone settings on the user's computer. And, indeed, that's the way JavaScript is set up to work.

How does new Date work JavaScript?

The Date object is an inbuilt datatype of JavaScript language. It is used to work with dates and times. The Date object is created by using new keyword, i.e. new Date(). The Date object can be used date and time in terms of millisecond precision within 100 million days before or after 1/1/1970.


1 Answers

var date = new Date();
date.setHours( 0,0,0,0 );

setHours() actually has two effects:

  1. It modifies the object it is applied to
  2. It returns the new timestamp of that date object

So in your case, just create the object and set the time separately afterwards. You can then ignore the return value entirely, if you don't need it.

like image 50
Sirko Avatar answered Oct 08 '22 01:10

Sirko