JavaScript: Fast parsing of yyyy-mm-dd into year, month, and day numbers - Stack Overflow

admin2025-04-04  0

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
    }
}

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
    }
}
Share Improve this question asked May 12, 2011 at 21:31 JimmyJimmy 531 silver badge3 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 9

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)
};

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]
}

10 years later

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1743704689a215933.html

最新回复(0)