Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
    }
}
like image 506
Jimmy Avatar asked Feb 25 '23 05:02

Jimmy


1 Answers

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)
};
like image 198
SLaks Avatar answered Feb 26 '23 20:02

SLaks