如何在JavaScript中解析日期时间字符串的日期部分?
问题描述:
我有这个时间字符串如何在JavaScript中解析日期时间字符串的日期部分?
Tue, 20 Oct 2015 17:14:47 +0200
我需要从这个返回的日期部分。换句话说,从它得到date
,month
和year
。
目前我所做的:
pub_date = new Date("Tue, 20 Oct 2015 17:14:47 +0200")
day = pub_date.getDate()
month = pub_date.getMonth()
year = pub_date.getYear()
只有day
得到正确返回。 month
和year
返回错误结果。什么会更正确?
答
它应该是pub_date.getFullYear()
。 getYear()
已被弃用。
http://www.w3schools.com/jsref/jsref_getfullyear.asp
此外,当月返回一个数字从0到11,你应该创建几个月阵列和访问的getMonth
结果。
var months = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
month = months[pub_date.getMonth()];
或者,如果你使用的角度,你可以使用内置的日期过滤
{{ date | format: 'MMMM' }}
答
按照docs:
日期。 prototype.getMonth()
根据当地时间返回指定日期中的月份(0-11)。
Date.prototype.getFullYear()
按照本地时间返回年份指定日期(4位数字为4位数的年份)。
所以,你会想:
pub_date = new Date("Tue, 20 Oct 2015 17:14:47 +0200")
day = pub_date.getDate()
month = pub_date.getMonth() + 1
year = pub_date.getFullYear()
答
你期望究竟什么样的结果? .getMonth()应返回你09,因为monthes编号为0至11
使用.getFullYear(这是正确的),而不是得到年(),应该回报你2015年
什么是不正确的结果你看到了吗? – AtheistP3ace
当有疑问时...阅读手册https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date – charlietfl