Change ISO Date String to Date Object - JavaScript

前端 未结 8 1717
花落未央
花落未央 2021-01-01 08:54

I am stuck in a weird situation and unfortunately,even after doing some RnD and googling, i am unable to solve this problem.

I have a date string in ISO format, lik

8条回答
  •  长发绾君心
    2021-01-01 09:36

    I started of with kevinmicke's excellent answer, but since I needed this for a code generator, I was concerned with code size. Eventually I ended up with this:

    const parseDate = dateString => {
      const b = dateString.split(/\D+/);
      const offsetMult = dateString.indexOf('+') !== -1 ? -1 : 1;
      const hrOffset = offsetMult * (+b[7] || 0);
      const minOffset = offsetMult * (+b[8] || 0);  
      return new Date(Date.UTC(+b[0], +b[1] - 1, +b[2], +b[3] + hrOffset, +b[4] + minOffset, +b[5], +b[6] || 0));
    };

提交回复
热议问题