Skip to content Skip to sidebar Skip to footer

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;

Solution 1:

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

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

Solution 3:

10 years later 😅, If you want to extract Years from an array, this will help you:

jQuery:

functionsplitDate(date) {
      newDate = [];
    
      $.map(date, function (item) {
        arr = item.split("-");
        newDate.push(arr[0]);
      });
    
      return newDate;
    }

Traditional way 😀 :

constsplitDate = (date) => {
  const newDate = [];

  date.map(item => {
    let arr = item.split("-");
    newDate.push(arr[0]);
  });

  return newDate;
}

const dateArr = ['2013-22-22', '2016-22-22', '2015-22-22', '2014-22-22'];
const year = splitDate(dateArr);

console.log(year)

Post a Comment for "Javascript: Fast Parsing Of Yyyy-mm-dd Into Year, Month, And Day Numbers"