moment.js - UTC gives wrong date

后端 未结 2 704
無奈伤痛
無奈伤痛 2020-11-27 13:08

Why does moment.js UTC always show the wrong date. For example from chrome\'s developer console:

moment((\'07-18-2013\')).utc().format(\"YYYY-MM-DD\").toStri         


        
2条回答
  •  盖世英雄少女心
    2020-11-27 13:39

    Both Date and moment will parse the input string in the local time zone of the browser by default. However Date is sometimes inconsistent with this regard. If the string is specifically YYYY-MM-DD, using hyphens, or if it is YYYY-MM-DD HH:mm:ss, it will interpret it as local time. Unlike Date, moment will always be consistent about how it parses.

    The correct way to parse an input moment as UTC in the format you provided would be like this:

    moment.utc('07-18-2013', 'MM-DD-YYYY')
    

    Refer to this documentation.

    If you want to then format it differently for output, you would do this:

    moment.utc('07-18-2013', 'MM-DD-YYYY').format('YYYY-MM-DD')
    

    You do not need to call toString explicitly.

    Note that it is very important to provide the input format. Without it, a date like 01-04-2013 might get processed as either Jan 4th or Apr 1st, depending on the culture settings of the browser.

提交回复
热议问题