What method in date-fns that equivalent to moment().toISOString()
Asked Answered
M

3

5

My old code use momentjs, something like this :

moment(createdAt, 'YYYY-MM-DD HH:mm:ss').toISOString()

What is the equivalent method on date-fns that will reproduce same result ?

Mask answered 27/8, 2018 at 6:46 Comment(2)
post an example of createdAtScheldt
i wrote the origin format ( YYYY-MM-DD HH:mm:ss). for the example : "2018-08-27T14:15:39.777"Mask
S
5

Try this,

new Date(createAt).toISOString()
Scheldt answered 27/8, 2018 at 7:18 Comment(1)
Ah.. i just realize that toISOString() is javascript method. i thought it was moment's. thank you very much.Mask
H
1

date-fns has a function: formatISO() So, if you want to stay with date-fns you can write:

formatISO(new Date())
Hemorrhage answered 4/2, 2022 at 12:16 Comment(0)
T
0

Currently date fns formatISO does not support miliseconds, https://github.com/date-fns/date-fns/issues/2968

Consequence:

date.toISOString() != dateFns.formatISO(date) 

You should better use js native toISOString() (ECMAScript5)

If not available a polyfill could be used

if ( !Date.prototype.toISOString ) {
  ( function() {

    function pad(number) {
      if ( number < 10 ) {
        return '0' + number;
      }
      return number;
    }

    Date.prototype.toISOString = function() {
      return this.getUTCFullYear() +
        '-' + pad( this.getUTCMonth() + 1 ) +
        '-' + pad( this.getUTCDate() ) +
        'T' + pad( this.getUTCHours() ) +
        ':' + pad( this.getUTCMinutes() ) +
        ':' + pad( this.getUTCSeconds() ) +
        '.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) +
        'Z';
    };

  }() );
}
Tetraspore answered 16/4, 2023 at 6:21 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.