【问题标题】:How to parse the date portion of a datetime string in JavaScript?如何在 JavaScript 中解析日期时间字符串的日期部分?
【发布时间】:2015-10-20 20:14:14
【问题描述】:

我有这个日期时间字符串

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 返回错误的结果。哪个更正确?

【问题讨论】:

标签: javascript string date datetime


【解决方案1】:

应该是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()];

或者如果你使用 angular,你可以使用内置的日期过滤器

{{ date | format: 'MMMM' }}

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

【讨论】:

  • 谢谢,现在一切都清楚了 :) 我会在 10 分钟内接受你的回答
  • month 的索引已关闭...您的数组也是从零开始的
  • 刚刚发现。谢谢
【解决方案2】:

根据docs

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

【讨论】:

    【解决方案3】:

    您到底期望什么结果? .getMonth() 应该返回 9,这是正确的,因为月份的编号是 0 到 11。

    使用 .getFullYear() 而不是 getYear(),应该会返回 2015 年。

    【讨论】:

      猜你喜欢
      • 2012-05-24
      • 2013-08-22
      • 1970-01-01
      • 1970-01-01
      • 2011-06-08
      • 2011-01-25
      • 1970-01-01
      • 2011-04-16
      相关资源
      最近更新 更多