JavaScript:将yyyy-mm-dd快速解析为年,月和日数

时间:2021-10-25 08:36:52

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

如何快速解析yyyy-mm-dd字符串(即“2010-10-14”)到其年,月和日数字?

A function of the following form:

以下形式的功能:

function parseDate(str) {    var y, m, d;    ...    return {      year: y,      month: m,      day: d    }}

2 个解决方案

#1


7  

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

#2


0  

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

您可以查看JavaScript split()方法 - 让您将字符串 - 字符拆分为数组。然后,您可以轻松获取这些值并将其转换为关联数组。

return {  year: result[0],  month: result[1],  day: result[2]}

#1


7  

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

#2


0  

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

您可以查看JavaScript split()方法 - 让您将字符串 - 字符拆分为数组。然后,您可以轻松获取这些值并将其转换为关联数组。

return {  year: result[0],  month: result[1],  day: result[2]}