Changing the Utc Date to Local Date using moment.j

2019-02-10 10:40发布

问题:

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. i want to convert the UTC time to the local Users time zone.

var timezone = "America/New_York";
var utcDate = "2013-10-16T10:31:59.0537721Z";

var localDate = moment(utcDate).utc().tz(timezone).format()

When i try to do this i'm getting wrong time. not sure how to get this working with moment

回答1:

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.



回答2:

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.


回答3:

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"


回答4:

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