Moment.js sets dates to 1 day behind

2020-07-10 06:36发布

问题:

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:

Example 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

Formatting function:

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

Output: 06-05-18

Expected: 07-05-18

Example 2:

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

Formatting function:

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

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

回答1:

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

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.

this how ever would in fact work:

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')

and output: "06-05-18"

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.

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