如何在JavaScript中解析datetime字符串的日期部分
How to parse the date portion of a datetime string in JavaScript?
我有这个datetime字符串
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()
已弃用。
同样,月份返回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 根据文档:
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()
您究竟期望得到什么样的结果?. getmonth()应该返回9,这是正确的,因为月份的编号是0到11。
使用. getfullyear()而不是getYear(),它应该返回2015。
相关文章:
- json对象包含php DateTime,如何转换为漂亮的日期字符串
- 如何在 JavaScript 中向 Datetime 字符串添加分钟数
- 从JavaScript客户端发送到.NET的字符串格式的UTC日期正在转换为DateTime
- 在Where谓词中将DateTime转换为字符串
- 如何通过javascript从字符串datetime中获取分钟
- System.FormatException:字符串未被识别为有效的DateTime
- 如何解析格式为'的DateTime字符串;2014-10-02T12:00'作为本地
- 用javascript拆分DateTime字符串
- 如何在JavaScript中解析datetime字符串的日期部分
- 在节点Js中从字符串转换为DateTime
- JavaScriptSerializer不能识别日期字符串为DateTime
- 如何在ASP中转换DateTime形式的字符串日期.净c#
- 从Javascript中的.net DateTime JSON格式字符串中获取正确的日期值
- 如何将JavascriptSerializer序列化的DateTime字符串转换为Javascript日期对象
- Javascript/jQuery-DateTime到Date和Time分别为字符串
- 将DateTime字符串转换为表中的经过时间
- 转换“;长形“;datetime字符串转换为javascript日期对象
- JavaScript的dateTime字符串到秒
- Javascript日期字符串到python datetime对象
- 如何使DateTime字符串根据时区变化