Borislav Hadzhiev
Wed Jan 19 2022·2 min read
Photo by A. L.
To get an ISO date without the milliseconds:
.
character.0
.Z
to the end of the result.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 .
, which separates the seconds from the milliseconds.
The last step is to access the array element at index 0
and append the Z
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.
In other words, if the ISO string contains a dot, we split the string and remove the milliseconds part, otherwise 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.