[removed] Fast parsing of yyyy-mm-dd into year, mo

2019-01-12 07:36发布

How can I parse fast a yyyy-mm-dd string (ie. "2010-10-14") into its year, month, and day numbers?

A function of the following form:

function parseDate(str) {
    var y, m, d;

    ...

    return {
      year: y,
      month: m,
      day: d
    }
}

2条回答
forever°为你锁心
2楼-- · 2019-01-12 07:38

You can split it:

var split = str.split('-');

return {
    year: +split[0],
    month: +split[1],
    day: +split[2]
};

The + operator forces it to be converted to an integer, and is immune to the infamous octal issue.

Alternatively, you can use fixed portions of the strings:

return {
    year: +str.substr(0, 4),
    month: +str.substr(5, 2),
    day: +str.substr(8, 2)
};
查看更多
甜甜的少女心
3楼-- · 2019-01-12 08:00

You could take a look at the JavaScript split() method - lets you're split the string by the - character into an array. You could then easily take those values and turn it into an associative array..

return {
  year: result[0],
  month: result[1],
  day: result[2]
}
查看更多
登录 后发表回答