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
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();
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!
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.
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.
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.
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 obejctmoment(Number)
creates a new moment object in the user's local time zone, using the passed in unix offset.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With