2015-10-20 140 views
0

我有这个时间字符串如何在JavaScript中解析日期时间字符串的日期部分?

Tue, 20 Oct 2015 17:14:47 +0200

我需要从这个返回的日期部分。换句话说,从它得到datemonthyear

目前我所做的:

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得到正确返回。 monthyear返回错误结果。什么会更正确?

+0

什么是不正确的结果你看到了吗? – AtheistP3ace

+1

当有疑问时...阅读手册https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date – charlietfl

回答

3

它应该是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' }} 

https://docs.angularjs.org/api/ng/filter/date

+0

谢谢,这使得一切都清除了:)我会接受你的回答在10分钟内 – Xeen

+1

索引是关闭的'月'...你的阵列也是零基于 – charlietfl

+0

刚刚发现。谢谢 –

1

按照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() 
1

你期望究竟什么样的结果? .getMonth()应返回你09,因为monthes编号为0至11

使用.getFullYear(这是正确的),而不是得到年(),应该回报你2015年