Reputation: 3924
We are passing a JSON date into Moment Timezone JS. We set our timezone in the moment.tz() call to specify the timezone we want the time to show up for everyone regardless of what the local timezone is of the user. Our issue is that I want to now convert it back to the default Javascript time format but KEEP the moment.tz() specified timezone. I tried wrapping the moment.tz() in a new Date() and appending the .toDate() but that just outputs the local date from the user's computer (I set my machines timezone to something other than my own to test this). What I want it to do is give me the specific timezone date/time that I specified as the time I specified in Moment.
Example of my output.
//1504897200000 = 1:00 pm on Friday September 8, 2017
var eventTimeDate = moment.tz(1504897200000, "America/Denver").format('h:mm A');
Now I want to take my JSON date and convert it back to the default Javascript format which should be:
Fri Sep 08 2017 13:00:00 GMT-0600 (Mountain Daylight Time)
But if I change my timezone on my local computer it shows up as the timezone of my computer setting NOT the timezone I set in Moment.js
So if I set my timezone to Dublin trying to convert the Moment time using the moment.tz() method
var eventTimeDateValue = moment.tz(1504897200000, "America/Denver").toDate();
It outputs:
Fri Sep 08 2017 20:00:00 GMT+0100 (GMT Daylight Time)
Which does not match the "America/Denver" setting I have in the Moment JS. I would lke it to be the:
Fri Sep 08 2017 13:00:00 GMT-0600 (Mountain Daylight Time)
Any ideas on how to convert it back to the long format but still keep the Moment JS set timezone?
Here is my JSFiddle:
https://jsfiddle.net/549La2ct/
Upvotes: 1
Views: 283
Reputation:
If you use toDate()
, it'll create a JavaScript Date object, and it doesn't provide a way to control the output the way you want.
If you want a string in the desired format, you can use format()
method, with an addition suggested in the docs to get the timezone long names:
var abbrs = {
EST : 'Eastern Standard Time',
EDT : 'Eastern Daylight Time',
CST : 'Central Standard Time',
CDT : 'Central Daylight Time',
MST : 'Mountain Standard Time',
MDT : 'Mountain Daylight Time',
PST : 'Pacific Standard Time',
PDT : 'Pacific Daylight Time',
};
moment.fn.zoneName = function () {
var abbr = this.zoneAbbr();
return abbrs[abbr] || abbr;
};
var str = moment.tz(1504897200000, "America/Denver").format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ (zz)');
The variable str
will have the value:
Fri Sep 08 2017 13:00:00 GMT-0600 (Mountain Daylight Time)
Upvotes: 2