Changing the Utc Date to Local Date using moment.js

后端 未结 4 1936
忘掉有多难
忘掉有多难 2020-12-17 02:01

i\'m using moment.js with timezones for date manipulation in a webapp. i\'m storing all the dates in UTC and return them to UI as UTC. I\'m having the timezone of the user.

相关标签:
4条回答
  • 2020-12-17 02:41

    You can try:

    moment.utc(utcDate).tz(timezone).format()
    

    But it shouldn't matter. They should both produce: "2013-10-16T06:31:59-04:00".

    It works for me, running on Chrome 30, so it's probably browser related.

    If you're running Moment.js 2.3.1 or earlier on IE8, then it's a side effect of issue #1175, which was fixed in 2.4.0. Updating to the latest version should solve the problem.

    0 讨论(0)
  • for anyone having the same problem:

    your date iso format should contain the timezone. here is the format allowed by momentjs:

    YYYY-MMM-DDTHH:mm:ss+00:00
    

    notice the +00:00 mean it is UTC

    example

    moment('2014-10-03T09:31:18+00:00').format()
    

    will terturn

    "2014-10-03T17:31:18+08:00"
    
    0 讨论(0)
  • 2020-12-17 03:01

    Use the + operator to get unix time, then:

    moment(+moment.utc(utcDate))
    

    How it works:

    • moment.utc(String) parses the string and returns a moment object set to UTC timezone.
    • + returns the unix offset in milliseconds for the moment obejct
    • moment(Number) creates a new moment object in the user's local time zone, using the passed in unix offset.
    0 讨论(0)
  • 2020-12-17 03:04

    Even if you don't know the timezone, you get the client offset and use like this,

    let utcTime = "2017-02-02 08:00:13.567";
    var offset = moment().utcOffset();
    var localText = moment.utc(utcTime).utcOffset(offset).format("L LT");
    

    Try this JsFiddle

    0 讨论(0)
提交回复
热议问题