简体   繁体   English

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

[英]How to parse the date portion of a datetime string in JavaScript?

I have this datetime string 我有这个日期时间字符串

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

I need to return the date portion from this. 我需要从中返回日期部分。 In other words, get date , month and year from it. 换句话说,从中获取datemonthyear

Currently I've done: 目前,我已经完成:

pub_date = new Date("Tue, 20 Oct 2015 17:14:47 +0200")
day      = pub_date.getDate()
month    = pub_date.getMonth()
year     = pub_date.getYear()

Only the day gets returned correctly. 只有day可以正确返回。 month and year return the wrong results. monthyear返回错误的结果。 What would be more correct? 哪个更正确?

It should be pub_date.getFullYear() . 它应该是pub_date.getFullYear() getYear() has been deprecated. getYear()已被弃用。

http://www.w3schools.com/jsref/jsref_getfullyear.asp http://www.w3schools.com/jsref/jsref_getfullyear.asp

Also, the month returns a number from 0 to 11. You should create a months array and access the result of getMonth . 另外,month返回一个从0到11的数字。您应该创建一个months数组并访问getMonth的结果。

var months = ["January", "February", "March", "April", "May", "June", "July", 
              "August", "September", "October", "November", "December"];
month = months[pub_date.getMonth()];

Or if you're using angular, you can use the built-in date filter 或者,如果您使用的是角度格式,则可以使用内置的日期过滤器

{{ date | format: 'MMMM' }}

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

According to the docs : 根据文档

Date.prototype.getMonth() Date.prototype.getMonth()

Returns the month (0-11) in the specified date according to local time. 根据当地时间返回指定日期的月份(0-11)。

Date.prototype.getFullYear() Date.prototype.getFullYear()

Returns the year (4 digits for 4-digit years) of the specified date according to local time. 根据当地时间返回指定日期的年份(4位年份为4位数字)。

So you'd want: 因此,您需要:

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()

What results do you expect exactly ? 您究竟期望得到什么结果? .getMonth() should return you 9, which is correct because monthes are numbered 0 to 11. .getMonth()应该返回9,这是正确的,因为月份的编号为0到11。

Use .getFullYear() instead of getYear(), that should return you 2015. 使用.getFullYear()而不是getYear(),应该会返回2015。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM