Remove the Seconds and Milliseconds from a Date in JS

avatar

Borislav Hadzhiev

Last updated: Jan 19, 2022

banner

Photo from Unsplash

Remove the Seconds and Milliseconds from a Date in JS #

Use the setSeconds() method to remove the seconds and milliseconds from a date, e.g. date.setSeconds(0, 0). The setSeconds method takes the seconds and milliseconds as parameters and sets the provided values on the date.

index.js
const dateStr = '2022-07-21T09:35:31.820Z'; const date = new Date(dateStr); date.setSeconds(0, 0); console.log(date); // 👉️ Thu Jul 21 2022 12:35:00 GMT+0300

The two parameters we passed to the Date.setSeconds method are:

  1. seconds - an integer between 0 and 59 that represents the seconds.
  2. milliseconds - a number between 0 and 999 that represents the milliseconds.

The method changes the values of the seconds and milliseconds on the Date object in place.

You can log the ISO representation of the date to see the result.

index.js
const dateStr = '2022-07-21T09:35:31.820Z'; const date = new Date(dateStr); date.setSeconds(0, 0); console.log(date); // 👉️ Thu Jul 21 2022 12:35:00 GMT+0300 // ✅ Seconds and milliseconds removed from date console.log(date.toISOString()); // 👉️ "2022-07-21T09:35:00.000Z"

You can see the difference between the value of the dateStr variable and the value we logged on the last line.

If you don't want to mutate the Date object in place, you can create a copy of it before using the setHours method.

index.js
const dateStr = '2022-07-21T09:35:31.820Z'; const date = new Date(dateStr); // ✅ Create copy of the Date const copyDate = new Date(date.getTime()); copyDate.setSeconds(0, 0); console.log(copyDate); // 👉️ Thu Jul 21 2022 12:35:00 GMT+0300

The set* methods like setHours, setMinutes and setSeconds mutate the Date object in place, which might not always be what you want.

The getTime method returns the number of milliseconds elapsed between the 1st of January, 1970 and the given date.

We can use this timestamp to create a new Date object with the same date and time, which we can mutate in place.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.