I use the Moment.js and Moment-Timezone frameworks, and have a Moment.js date object which is explicitly in UTC timezone. How can I convert that to the current timezone of the browser?
var testDateUtc = moment.tz("2015-01-30 10:00:00", "UTC"); var localDate = ???
So it would be fine if I could find out the users local time zone; or alternatively I'd like to convert the date object into another data object which just uses the "local timezone", no matter what that actually is.
To get a list of all available time zone names, use moment. tz. names . moment.
To convert UTC time to Local you have to use moment. local() .
Date Formatting Date format conversion with Moment is simple, as shown in the following example. moment(). format('YYYY-MM-DD'); Calling moment() gives us the current date and time, while format() converts it to the specified format.
You do not need to use moment-timezone for this. The main moment.js library has full functionality for working with UTC and the local time zone.
var testDateUtc = moment.utc("2015-01-30 10:00:00"); var localDate = moment(testDateUtc).local();
From there you can use any of the functions you might expect:
var s = localDate.format("YYYY-MM-DD HH:mm:ss"); var d = localDate.toDate(); // etc...
Note that by passing testDateUtc
, which is a moment
object, back into the moment()
constructor, it creates a clone. Otherwise, when you called .local()
, it would also change the testDateUtc
value, instead of just the localDate
value. Moments are mutable.
Also note that if your original input contains a time zone offset such as +00:00
or Z
, then you can just parse it directly with moment
. You don't need to use .utc
or .local
. For example:
var localDate = moment("2015-01-30T10:00:00Z");
var dateFormat = 'YYYY-DD-MM HH:mm:ss'; var testDateUtc = moment.utc('2015-01-30 10:00:00'); var localDate = testDateUtc.local(); console.log(localDate.format(dateFormat)); // 2015-30-01 02:00:00
See: http://momentjs.com/docs/#/manipulating/local/
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