JavaScript - remove milliseconds from date object

Viewed 18096

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?

5 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");

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

you can use setMilliseconds on the Date object to set the wanted miliseconds amount.

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

Example output:

2022-06-12T13:00:00.000Z

One other option:

var date = new Date();
date.setMilliseconds(0);
var dateISOString = date.toISOString().replace(".000Z", "Z");

console.log(dateISOString);

OUTPUT:

2021-06-16T10:08:41Z

It's milliseconds you see, which you can also remove like below. Also you can use .setHours() only to remove mins and seconds.

var sun = new Date();
sun.setDate(sun.getDate() + (7 - sun.getDay()));
sun.setHours(9,0,0,0)
console.log(sun.toISOString().slice(0,-5) + 'Z');

Related