Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the Utc Date to Local Date using moment.js

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

like image 945
Anto Subash Avatar asked Oct 16 '13 10:10

Anto Subash


People also ask

How do you convert UTC to moments in dates?

To convert date to UTC using moment. js and JavaScript, we can use the moment's utc method. const utcStart = new moment("2022-06-24T09:00", "YYYY-MM-DDTHH:mm"). utc();

How do you convert UTC time to local time in node js?

Use the Date() constructor to convert UTC to local time, e.g. new Date(utcDateStr) . Passing a date and time string in ISO 8601 format to the Date() constructor converts the UTC date and time to local time. Copied!

How do I change the date format in a moment?

moment(). format('YYYY-MM-DD'); Calling moment() gives us the current date and time, while format() converts it to the specified format. This example formats a date as a four-digit year, followed by a hyphen, followed by a two-digit month, another hyphen, and a two-digit day.

What is moment UTC?

moment. utc(); moment. utc can take params as number, string, moment, date etc. This method can be used when the date displayed has to be in UTC format.


2 Answers

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.

like image 91
Matt Johnson-Pint Avatar answered Nov 08 '22 21:11

Matt Johnson-Pint


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.
like image 43
bguiz Avatar answered Nov 08 '22 23:11

bguiz