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 = 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.


Solution 2:

// Create date.  Left empty, will default to 'now'
var myDate = new Date();

// Set hours
myDate.setHours(7);

// Then set minutes
myDate.setMinutes(15);

// Then set seconds
myDate.setSeconds(47);

Solution 3:

var date = new Date()
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 = new Date(); // 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 = new Date().setHours(0, 0, 0, 0);
var date = new Date(timestamp); // Midnight today 00:00:00.000
var hourBeforeMidnight = timestamp - (60 * 60 * 1000);
var otherDate = new Date(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"