Moment.js将日期设置为晚1天 [英] Moment.js sets dates to 1 day behind

查看:2059
本文介绍了Moment.js将日期设置为晚1天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用2.22.1格式化日期.

I am using 2.22.1 to format dates.

当我输入来自日期选择器的日期时,此刻会将日期放回一天.例如,当我尝试通过以下方式格式化日期时:

When i put in a date that comes from a date selector, moment will put the date back one day. For example, when I try to format a date in the following way:

示例1:

const day = new Date(value).getDate();
const month = new Date(value).getMonth();
const fullYear = new Date(value).getFullYear();
console.log('day', day); // 7
console.log('month', month); // 5
console.log('fullYear', fullYear); //2018

格式化功能:

moment.utc(new Date(month + ' ' + day + ' ' + fullYear), 'MM-DD-YYYY').format('DD-MM-YY')

输出:18年6月5日

预计:18年7月5日

示例2:

输入:2018年5月31日,星期四00:00:00 GMT + 0100(GMT夏令时)

Input: Thu May 31 2018 00:00:00 GMT+0100 (GMT Summer Time)

格式化功能:

moment.utc(new Date(value)).format('DD-MM-YY')

输出:30-05-18 预计:31-05-18

Output: 30-05-18 Expected: 31-05-18

推荐答案

moment.utc会将输入转换为通用时间.
您正在运行new Date(...),并且输入基于GMT +1

moment.utc will convert the input to universal time.
you are running new Date(...) with an input that's based on GMT +1

如果您考虑这个问题,那将是很有意义的.
您的输出是30-05-18,因为它是前一天的11 PM/23:00.

if you think about this, it makes total sense.
your output is 30-05-18 because it's 11 PM / 23:00 o'clock on the previous day.

这实际上将如何工作:

moment('05-06-2018', 'MM-DD-YYYY').format('DD-MM-YY')
// alternatively (and preferrably) this:
moment.utc('05-06-2018', 'MM-DD-YYYY').format('DD-MM-YY')

并输出:"06-05-18"

moment.js存在的原因之一是一起删除了代码中的Date.
请阅读有关如何正确使用力矩的文档.

one of the reasons moment.js exists, is to get rid of Date in your code all together.
please just read the documentation on how to properly use moment.

如果您想以此处理400000个日期,我建议改用regexp.

if you want to process 400000 dates with this, i'd advise using regexp instead.

这篇关于Moment.js将日期设置为晚1天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆