moment.js - UTC gives wrong date

后端 未结 2 690
無奈伤痛
無奈伤痛 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

    By default, MomentJS parses in local time. If only a date string (with no time) is provided, the time defaults to midnight.

    In your code, you create a local date and then convert it to the UTC timezone (in fact, it makes the moment instance switch to UTC mode), so when it is formatted, it is shifted (depending on your local time) forward or backwards.

    If the local timezone is UTC+N (N being a positive number), and you parse a date-only string, you will get the previous date.

    Here are some examples to illustrate it (my local time offset is UTC+3 during DST):

    >>> moment('07-18-2013', 'MM-DD-YYYY').utc().format("YYYY-MM-DD HH:mm")
    "2013-07-17 21:00"
    >>> moment('07-18-2013 12:00', 'MM-DD-YYYY HH:mm').utc().format("YYYY-MM-DD HH:mm")
    "2013-07-18 09:00"
    >>> Date()
    "Thu Jul 25 2013 14:28:45 GMT+0300 (Jerusalem Daylight Time)"
    

    If you want the date-time string interpreted as UTC, you should be explicit about it:

    >>> moment(new Date('07-18-2013 UTC')).utc().format("YYYY-MM-DD HH:mm")
    "2013-07-18 00:00"
    

    or, as Matt Johnson mentions in his answer, you can (and probably should) parse it as a UTC date in the first place using moment.utc() and include the format string as a second argument to prevent ambiguity.

    >>> moment.utc('07-18-2013', 'MM-DD-YYYY').format("YYYY-MM-DD HH:mm")
    "2013-07-18 00:00"
    

    To go the other way around and convert a UTC date to a local date, you can use the local() method, as follows:

    >>> moment.utc('07-18-2013', 'MM-DD-YYYY').local().format("YYYY-MM-DD HH:mm")
    "2013-07-18 03:00"
    

提交回复
热议问题