Javascript 时刻js从字符串中提取年份
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12723482/
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
moment js extract year from string
提问by Mauro74
I'm new to moment.js and I can't really understand the documentation. I'd like to manipulate some dates in string format.
我是 moment.js 的新手,我无法真正理解文档。我想以字符串格式操作一些日期。
I have my date as string from json feed and looks like:
我的日期是来自 json 提要的字符串,看起来像:
var year = item.date
// it returns a string like "25/04/2012"
How do I extract the year from it using moment.js ?
如何使用 moment.js 从中提取年份?
回答by Luca
You can use
您可以使用
moment("25/04/2012","DD/MM/YYYY").format("YYYY")
or
moment("25/04/2012","DD/MM/YYYY").year()
in your example:
在你的例子中:
moment(item.date,"DD/MM/YYYY").year()
回答by acabaral
Or you can convert the string to date then extract the year:
或者您可以将字符串转换为日期然后提取年份:
var date = new Date(dateString);
if (!isNaN(date)) {
return d.getFullYear();
}