公告
财富商城
积分规则
提问
发文
2019-04-07 15:40发布
对你真心纯属浪费
Given a date in the following string format:
2010-02-02T08:00:00Z
How to get the year with JavaScript?
var year = '2010-02-02T08:00:00Z'.substr(0,4)
...
var year = new Date('2010-02-02T08:00:00Z').getFullYear()
It's a date, use Javascript's built in Date functions...
var d = new Date('2011-02-02T08:00:00Z'); alert(d.getFullYear());
You can simply use -
var dateString = "2010-02-02T08:00:00Z"; var year = dateString.substr(0,4);
if the year always remain at the front positions of the year string.
You can simply parse the string:
var year = parseInt(dateString);
The parsing will end at the dash, as that can't be a part of an integer (except as the first character).
I would argue the proper way is
var year = (new Date('2010-02-02T08:00:00Z')).getFullYear();
or
var date = new Date('2010-02-02T08:00:00Z'); var year = date.getFullYear();
since it allows you to do other date manipulation later if you need to and will also continue to work if the date format ever changes.
UPDATED: Jason Benson pointed out that Date will parse it for you. So I removed the extraneous Date.parse calls.
最多设置5个标签!
...
It's a date, use Javascript's built in Date functions...
You can simply use -
if the year always remain at the front positions of the year string.
You can simply parse the string:
The parsing will end at the dash, as that can't be a part of an integer (except as the first character).
I would argue the proper way is
or
since it allows you to do other date manipulation later if you need to and will also continue to work if the date format ever changes.
UPDATED: Jason Benson pointed out that Date will parse it for you. So I removed the extraneous Date.parse calls.