![](/img/trans.png)
[英]How to display previous day and next day dates in html using Javascript
[英]Dates display behind by a day
使用Moment.js时遇到一些奇怪的行为。 我在Date原型上附加了一些辅助类,这些辅助类显然导致每个日期都落后一天。
Date.prototype.format = function(){
return moment(this).format('MM/DD/YYYY')
}
var date = new Date('2008-05-13T00:00:00')
date.format() // => 05/12/2008, but should be 05/13/2008
我注意到了其他一些奇怪的事情:
date.getDate() // => yields 12, but should be 13
但是,如果我直接使用UTC字符串实例化Moment对象,那么它将起作用:
moment('2008-05-13T00:00:00').format('MM/DD/YY') // => 05/13/08
但是我正在处理普通日期对象,将每个日期修改为Moment对象并不是我的最爱。 我已经尝试过修改format
函数以从日期中提取UTC字符串,然后查看它是否正确显示,但无济于事。
date.toUTCString() // => Correctly yields "Tue, 13 May 2008 00:00:00 GMT"
moment(date.toUTCString()).format('MM/DD/YY') // => still 05/12/08
有什么想法吗? 日期构造函数有问题吗?
编辑:也输出时间:
moment(date).format('MM/DD/YY hh:mm:ss') // => "05/12/08 08:00:00"
您必须告诉moment.js您以UTC显示日期:
moment(this).utc().format('MM/DD/YYYY')
文档中的更多信息: http : //momentjs.com/docs/#/parsing/utc/
但是,如果我直接使用UTC字符串实例化Moment对象,那么它将起作用:
moment('2008-05-13T00:00:00').format('MM/DD/YY') // => 05/13/08`
Moment.js 将参数解释为本地时间 :
默认情况下,moment解析并以本地时间显示。
而new Date()
(和Date.parse
) 将值解释为UTC时间 :
parse
函数将生成的字符串解释为日期和时间。 它返回一个数字,即与日期和时间相对应的UTC时间值。
我已经尝试过修改格式函数以从日期中提取UTC字符串,然后查看它是否正确显示,但无济于事。
date.toUTCString() // => Correctly yields "Tue, 13 May 2008 00:00:00 GMT" moment(date.toUTCString()).format('MM/DD/YY') // => still 05/12/08`
date.toUTCString()
产生的格式不是moment.js支持的任何格式 ,因此它回退到使用new Date()
(它将字符串解释为UTC时间,而不是本地时间)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.