最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin8PV0评论

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

Post a comment

comment list (0)

  1. No comments so far