Skip to content Skip to sidebar Skip to footer

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); da

Solution 1:

var date = newDate();
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.

Solution 2:

//Create date.  Leftempty, will defaultto'now'
var myDate =newDate();

//Set hours
myDate.setHours(7);

//Thenset minutes
myDate.setMinutes(15);

//Thenset seconds
myDate.setSeconds(47);

Solution 3:

var date = newDate()
date.setUTCHours(15,31,01);

This will return a time of 15::31:01

More info here

Solution 4:

The way to do it, get midnight of the current day for example:-

var date = newDate(); // Datetime now
date.setHours(0, 0, 0, 0);
console.log(date); // Midnight today 00:00:00.000

The setHours function returns a timestamp rather than a Date object, but it will modify the original Date object.

The timestamp can be used to initialize new date objects and perform arithmetic.

var timestamp = newDate().setHours(0, 0, 0, 0);
var date = newDate(timestamp); // Midnight today 00:00:00.000var hourBeforeMidnight = timestamp - (60 * 60 * 1000);
var otherDate = newDate(hourBeforeMidnight); // Date one hour before

The timestamp is the same value you would get if you called getTime.

var timestamp = date.getTime();

Post a Comment for "Javascript Dates : Change Time"