Javascript Dates: Change Time

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

Oddities are those setters that return a Number object.

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

date is a number, not a date ..

so say i have date var date = new Date ()

and I want to change the time

thanks

+4
source share
5 answers
 var date = new Date(); date.setHours( 0,0,0,0 ); 

setHours() actually has two effects:

  • It modifies the object that it applies to
  • It returns the new timestamp of this date object.

So, in your case, just create an object and set the time separately. You can ignore the return value completely if you do not need it.

+7
source
 // 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); 
0
source

A way to do this, for example, get the midnight of the current day: -

 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, not a Date object, but it will change 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 that you would get if you called getTime .

 var timestamp = date.getTime(); 
0
source
 var date = new Date() date.setUTCHours(15,31,01); 

This will return the time 15 :: 31: 01

More here

0
source

This snippet converts the time to 0: 0: 0, which is necessary if you are going to filter data from zero o'clock in the afternoon. Useful for filtering ODATA by date.

  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); 
0
source

All Articles