Search code examples
javascriptnode.jsdatetimedate-fnslocaldatetime

How to convert "yyyy-MM-dd'T'HH:mm:ss 'GMT'Z" to localDateTime using date-fns


I'm getting a DateTime in the following format

"yyyy-MM-dd'T'HH:mm:ss 'GMT'Z" // -> 2021-07-02T10:09:07:715 GMT+0000

I want to convert it to my local DateTime. I tried to do that in date-fns (javascript).

const createTime ="2021-07-02T10:09:07:715 GMT+0000";

console.log(parseISO(createTime.substring(0, 19))); // -> 2021-07-02T04:09:07.000Z

  console.log(
    parseISO(createTime.substring(0, 19)).toString()
  ); // -> Fri Jul 02 2021 10:09:07 GMT+0600 (Bangladesh Standard Time)
  
  // at that time my local DateTime as follow

  console.log(new Date()); // -> 2021-07-02T10:09:07.750Z

  console.log(new Date().toString()); // -> Fri Jul 02 2021 16:09:07 GMT+0600 (Bangladesh Standard Time)

but it's not converting to my local time for whatever reason.

Is there any other way to convert this type of formatted DateTime to local date-time?

if so please help...

Note: I'm using date-fns in Node.js..


Solution

  • You don't have to do anything to the input string, you just have to use the right parse tokens and format. The OP has:

    "yyyy-MM-dd'T'HH:mm:ss 'GMT'Z"
    

    Which, given an input string like '2021-07-02T10:09:07:715 GMT+0000', has the following errors:

    1. Missing a token for the decimal seconds part and separating colon
    2. "Z" is the wrong token for the offset, it should be "X"

    So the correct parse tokens are:

    "yyyy-MM-dd'T'HH:mm:ss:SSS 'GMT'X"
    

    An example that can be run at npm.runkit.com:

    let parse = require('date-fns/parse');
    let d = parse('2021-07-02T10:09:07:715 GMT+0000', "yyyy-MM-dd'T'HH:mm:ss:SSS 'GMT'X", new Date());
    console.log(d.toISOString());
    

    Alternatively, you can parse the string yourself, e.g.

    function parseSpecial(s) {
      // Get the parts of the timestamp
      let [y, m, d, H, M, S, ms, offset] = s.match(/\d+|a-z+|[+-]\d{4}$/g);
      // Get the offset sign
      let offSign = offset.substr(0,1)
      // Convert offset to minutes
      let offMins = (offset.substr(1, 2)*60 + +offset.substr(3, 2)) * (offSign == '+'? 1 : -1);
      // Create a Date, adjusted by the offset
      return new Date(Date.UTC(y, m-1, d, H, M-offMins, S, ms));
    }
    
    ['2021-07-02T10:09:07:715 GMT+0000',
     '2021-07-02T10:09:07:715 GMT+0530',
     '2021-07-02T10:09:07:715 GMT-0400'
    ].forEach(s => console.log(parseSpecial(s).toString()));