admin管理员组文章数量:1026989
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
3 Answers
Reset to default 9You 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
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
3 Answers
Reset to default 9You 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
本文标签: JavaScript Fast parsing of yyyymmdd into yearmonthand day numbersStack Overflow
版权声明:本文标题:JavaScript: Fast parsing of yyyy-mm-dd into year, month, and day numbers - Stack Overflow 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://it.en369.cn/questions/1743704686a2015625.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论