简体   繁体   English

不正确的日期格式 moment.js

[英]Incorrent day format moment.js

I have an input with the following date inside my util function (the first argument) - '2013-12-15'.我的 util function(第一个参数)-'2013-12-15' 中有一个带有以下日期的输入。 I use the format 'MM/DD/YYYY' as a second argument for the format moment.js method.我使用格式“MM/DD/YYYY”作为格式 moment.js 方法的第二个参数。 Actual result: 12/14/2013 instead of 12/15/2013 (input date equals to '2013-12-15').实际结果:12/14/2013 而不是 12/15/2013(输入日期等于 '2013-12-15')。 The question is - why moment subtract one day after formatting?问题是 - 为什么在格式化后减去一天?

export const formatDateTime = (date, format = MM/DD/YYYY) => {
    let useFormat = format

    return moment
        .utc(date)
        .tz('America/New_York')
        .format(useFormat)
} // return '12/14/2013'

I don't know the reason for reducing a day, but one way you can do to format the date would be using regular expression like this:我不知道减少一天的原因,但是您可以采取的一种格式化日期的方法是使用如下正则表达式:

 const formatDate = date => { let regX = /(\d+)\/(\d+)\/(\d+)/ // AAAA-MM-DD return date.replace(regX, '$2/$3/$1') }

You're providing a timezone for moment.您正在提供一个时区。 Moment will create a Date object and the date is going to be something like 2013-12-15T00:00:00Z , then moment will apply timezone, thus date will become 2013-12-14T18:00:00Z . Moment 将创建一个 Date object 并且日期将类似于2013-12-15T00:00:00Z ,然后 moment 将应用时区,因此日期将变为2013-12-14T18:00:00Z This is not 100% corrent这不是 100% 正确的

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

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