Get ISO Date without the Milliseconds using JavaScript


Borislav Hadzhiev

Last updated: Jul 24, 2022


Photo from Unsplash

Get ISO Date without the Milliseconds using JavaScript #

To get an ISO date without the milliseconds:

  1. Split the ISO string on the dot . character.
  2. Access the array element at index 0.
  3. Append the letter Z to the end of the result.
  4. For example, date.toISOString().split('.')[0] + 'Z'.
// ✅ If you have a Date object const date = new Date(); const withoutMs = date.toISOString().split('.')[0] + 'Z'; console.log(withoutMs); // 👉️ "2022-01-19T07:32:40Z" // ✅ If you have a plain ISO string const isoStr = '2022-07-21T09:35:31.820Z'; const withoutMilliseconds = isoStr.split('.')[0] + 'Z'; console.log(withoutMilliseconds); // 👉️ "2022-07-21T09:35:31Z"

The split method splits a string on the provided separator and returns an array of substrings.

const isoStr = '2022-07-21T09:35:31.820Z'; // 👇️ ['2022-07-21T09:35:31', '820Z'] console.log(isoStr.split('.'));

ISO formatted dates look like: YYYY-MM-DDTHH:mm:ss.sssZ, so we can split the string on the dot . that separates the seconds from the milliseconds.

The last step is to access the array element at index 0 and append the Z character.

If your ISO strings might not contain the dot and milliseconds for some reason, it's best to use a ternary operator to check before splitting on a non-existent character.
const isoStr = '2022-07-21T09:35:31Z'; const withoutMilliseconds = isoStr.includes('.') ? isoStr.split('.')[0] + 'Z' : isoStr; // 👇️ "2022-07-21T09:35:31Z" console.log(withoutMilliseconds);

We used the String.includes method to check if the ISO string contains a dot . character.

The ternary operator is very similar to in if/else statement.

If the condition to the left of the question mark returns a truthy value, the value to the left of the colon in returned, otherwise the value to the right is returned.

In other words, if the ISO string contains a dot, we split the string and remove the milliseconds part, otherwise we return the string as is.

You only have to do this if your ISO string might not contain the milliseconds part, e.g. because you already removed it, or it was never there to begin with.

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.