Search code examples
javascriptdateutc

Stripping milliseconds from Extended ISO format


Javascript's Date.toISOString() function returns a string in the following format:

YYYY-MM-DDTHH:mm:ss.sssZ

How can I strip the milliseconds from such a string? That is, I desire a string in this format:

YYYY-MM-DDTHH:mm:ssZ


Solution

  • Since ISO date format is fixed width up until the millisecond portion, an alternative to splitting on the '.' is to simply use substring, then replace the "Z" timezone designator:

    var d = new Date()
    
    d.toISOString().substring(0,19)+'Z'
    
    "2015-07-01T21:27:45Z"