1

I'm currently working with Moment.js which is used to convert one time zone to another. I read the document and when I tried it doesn't give any suitable result.

Right now, I'm doing the following for converting a local time to some other time zone (for eg. America/Toronto).

var dt = moment();
alert(moment.utc(dt.local()).tz("America/Toronto").format());

At the second line of code, I converted the local time to utc and then the timezone name, to which the local time zone to be converted. but the time zone alerted is the UTC time of local time. I don't know what I have done wrong.

Any help would be appreciable.

Huangism
  • 16,278
  • 7
  • 48
  • 74
RajeshKannan
  • 894
  • 2
  • 16
  • 32

1 Answers1

2

You should be able to just do:

moment().tz("America/Toronto").format();

EDIT

As Matt Johnson pointed out in the comments, you're perhaps not including the moment-timezone data file.

Here is a fiddle to demonstrate (check out the external resources).

Dimitar Dimitrov
  • 14,868
  • 8
  • 51
  • 79
  • I tried, but it's giving the local time instead of giving America/Toronto time. – RajeshKannan Jul 14 '14 at 09:41
  • @Rajesh - This is the correct answer. Did you include the data file? – Matt Johnson-Pint Jul 14 '14 at 15:08
  • @MattJohnson Hi Matt, I'm pretty sure I've used this before, but for some reason it doesn't work for me now either (I'm trying to reproduce it in a fiddle: http://jsfiddle.net/Za6gE/1/ - as you can see in the external dependencies I've included the data file as well). – Dimitar Dimitrov Jul 14 '14 at 16:09
  • You had moment-timezone loaded twice. The "with data" file has the code also. I updated your fiddle and it works. – Matt Johnson-Pint Jul 14 '14 at 16:13
  • Also, note that in the latest 0.1.0 version of moment-timezone, things are a bit different in this regard. – Matt Johnson-Pint Jul 14 '14 at 16:13
  • @MattJohnson Wow, yeah, not sure how I missed that - thanks :) I'm pretty sure he's not including the data file. I've updated my answer, hopefully it will be helpful. – Dimitar Dimitrov Jul 14 '14 at 16:15
  • @MattJohnson Wow, that was quick :) Sometimes you gotta love OSS :) – Dimitar Dimitrov Jul 14 '14 at 16:27
  • @MattJohnson and Dimitar thank u for the reply. Your solution guided me in a right path and I have already loaded data file but the mistake I have done is, I loaded the data file after the moment-timezone.js and when I loaded the data file first then it worked fine. Thank u guyzz..:) – RajeshKannan Jul 14 '14 at 19:50