Search code examples
javascriptmomentjsiso8601

Convert ISO 8601 to a different ISO 8601 format using MomentJS


Is there a way for a format like this:

2003-09-25T14:00:00.000+1000 or 2003-09-25T14:00:00.000+1100

To be converted like this

2003-09-25T14:00:00.000Z

Without using manual and only using MomentJS. I also want to know what +1000 or +1100 means.


Solution

  • It's possible to get the offset hours and add them back to the time.

    var timeStrings = [
      '2003-09-25T14:00:00.000+1000',
      '2003-09-25T14:00:00.000+1100'
    ];
    
    console.log(timeStrings.map(ts => {
      var m = moment(ts);
      m.add(m._tzm, 'minutes'); // Add total minute offset
      return m.toISOString();
    }));
    .as-console-wrapper { top: 0; max-height: 100% !important; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>


    Alternative approach that does not modify the moment objects when displayed.

    var timeStrings = [
      '2003-09-25T14:00:00.000+1000',
      '2003-09-25T14:00:00.000+1100'
    ];
    var moments = timeStrings.map(ts => moment(ts));
    
    // The moments are not modified when displayed...
    console.log(moments.map(momentDateAsUtc));
    
    function momentDateAsUtc(m) {
      var clone = m.clone();
      clone.add(m._tzm, 'minutes'); // Add total minute offset
      return clone.toISOString();
    }
    .as-console-wrapper { top: 0; max-height: 100% !important; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>