30

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

4
  • 3
    var d = new Date(); d.setTime(1332403882588); Commented Dec 6, 2012 at 9:59
  • Sorry.. no it wont work.. I was not specific enough Commented Dec 6, 2012 at 10:02
  • Then use setHours(),setMinutes(),setSeconds() Commented Dec 6, 2012 at 10:03
  • if fact I dont vote for a useful comment Commented Dec 6, 2012 at 10:17

6 Answers 6

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

2
var date = new Date() date.setUTCHours(15,31,01); 

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

More info here

Comments

1

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

Comments

1

This Snippet will convert the time to 0:0:0 which is needed if you are going to filter data from zeroth hour of the day. Useful for ODATA filtering on Dates

 var a = new Array();	var b = new Array();	var c = new Array();	var date = new Date().toJSON();	a = date.split("T");	a = a[0];	b = a.split("-");	var currentDate = new Date(b[0],b[1] - 1, b[2] + 1 ,-19,30,0).toJSON();	c = currentDate.split(".");	var newDate = c[0]; console.log(newDate);

Comments

0

You can do it like this:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.