Home > Net >  how to convert date to iso 8601 in js
how to convert date to iso 8601 in js

Time:10-12

Hello I need to call an API and pass a date parameter, the backend has specified that it has to be ISO 8601. This is the example they gave me: 2020-01-01T00:00:00+01:00

the : is the escape character for :

the + is the escape character for  

if I do console.log(new Date().toISOString()) i just get 2021-10-12T13:13:27.633Z

The api fails when I pass it converted toISOString().

What can I do?

CodePudding user response:

I solved it. I did it like this:

    toIsoStringCustom(date: Date) {
    var tzo = -date.getTimezoneOffset(),
        dif = tzo >= 0 ? ' ' : '-',
        pad = function(num: number) {
            var norm = Math.floor(Math.abs(num));
            return (norm < 10 ? '0' : '')   norm;
        };

    return date.getFullYear()  
        '-'   pad(date.getMonth()   1)  
        '-'   pad(date.getDate())  
        'T'   pad(date.getHours())  
        ':'   pad(date.getMinutes())  
        ':'   pad(date.getSeconds())  
        dif   pad(tzo / 60)  
        ':'   pad(tzo % 60);
  }

let today = new Date()
console.log(encodeURIComponent(this.toIsoStringCustom(today)))

CodePudding user response:

What you are trying to achieve has nothing to do with the date format. It's simply encoded so. The encodeURIComponent() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

Check this snippet below:

console.log(encodeURIComponent("2021-10-12T13:13:27.633Z"));

  • Related