如何从 JavaScript 中的这个日期字符串解析年份?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4170117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to parse the year from this date string in JavaScript?
提问by Pierce Reed
Given a date in the following string format:
给定以下字符串格式的日期:
2010-02-02T08:00:00Z
How to get the year with JavaScript?
如何使用 JavaScript 获得年份?
采纳答案by Guffa
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).
解析将在破折号处结束,因为它不能是整数的一部分(第一个字符除外)。
回答by Jason Benson
回答by Rob Van Dam
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.
更新:Jason Benson 指出 Date 会为你解析它。所以我删除了无关的 Date.parse 调用。
回答by MD Sayem Ahmed
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.
如果年份始终保留在年份字符串的前面位置。
回答by alxndr
var year = '2010-02-02T08:00:00Z'.substr(0,4)
...
...
var year = new Date('2010-02-02T08:00:00Z').getFullYear()