Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - remove milliseconds from date object

I'm trying to get the date for the next Sunday (and set the time to 9am:

var sun = new Date();
sun.setDate(sun.getDate() + (7 - sun.getDay()));
sun.setHours(9);
sun.setMinutes(0);
sun.setSeconds(0);
console.log(sun.toISOString());

This is what I get:

  2018-11-04T09:00:00.722Z

The only thing that I don't need is .722 (API will not accept that)

2018-11-04T09:00:00Z

How do I remove the .722 bit?

like image 859
Wasteland Avatar asked Oct 28 '18 15:10

Wasteland


2 Answers

Try to split your toISOString() with . using String.prototype.split(), grab the 0th index and concatenate the literal Z with the output. This way you can simply ignore the 1st index that contains the milliseconds value. Hope this helps :)

var sun = new Date();
sun.setDate(sun.getDate() + (7 - sun.getDay()));
sun.setHours(9);
sun.setMinutes(0);
sun.setSeconds(0);
console.log(sun.toISOString().split('.')[0]+"Z");
like image 197
Always Sunny Avatar answered Sep 28 '22 06:09

Always Sunny


One option might be to do a regex replacement on the timestamp string, after you have generated it:

var ts = "2018-11-04T09:00:00.722Z";
console.log(ts);
ts = ts.replace(/\.\d+/, "");
console.log(ts);
like image 21
Tim Biegeleisen Avatar answered Sep 28 '22 06:09

Tim Biegeleisen