Home > database >  How to format ISO strings without milliseconds?
How to format ISO strings without milliseconds?

Time:10-14

I have date-time strings in different ISO formats which I have to compare for equality. I can only use the moment.js library for working with dates.

Example 1 - 2022-10-15T20:00:00Z
Example 2 - 2022-10-15T20:00:00.0459273Z

I want to convert both date-time strings to the format seen in example 1 and then compare them as strings. How do I convert the strings with moment.js? Is there a way to specify an ISO format which looks like example 1, or do I have to use string replacement to make date-time strings comparable. I see that moment(timeString).toISOString() does not work for this because it gives a time format like 2016-11-22T17:00:00.000Z which is not like example 1.

CodePudding user response:

You can try formatting the ISO string returned from moment(timeString).toISOString() to the example 1 format:

console.log("2016-11-22T17:00:00.000Z".split('.')[0] "Z")

CodePudding user response:

I found the solution. We can specify a format like this:

moment(someDateString).format('YYYY-MM-DD[T]HH:mm:ss[Z]')

The square brackets escape characters (such as YYYY, MM etc.) in format strings. Then perform a string comparison.

  • Related