Pradyut Bhattacharya
Pradyut Bhattacharya

Reputation: 5748

converting to local time from timezone offset using moment.js

I m having a datetime with timezone offset in a DOM. It looks like -

<div id="some">2014-09-26 23:57:02 +0530</div>

Now In chrome I able to convert it to local browser's time using the code below with moment.js.

In FF it complains invalid time and IE throws the time as it is. The example fiddle here.

The code -

 jQuery.fn.extend({
    convertTime: function(format) {
     return this.each(function(i, e) {
         var txt = $(e).html() ;
         try {
            $(e).html(  moment(txt).format('YYYY-MM-DD HH:mm:ss'));
         } catch(err) {console.log (err.message);$(e).html(txt);}
    });
  }
});

Upvotes: 0

Views: 1100

Answers (1)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241890

Pass a format string to moment so it won't fall back to the brower's date parser.

moment(txt,'YYYY-MM-DD HH:mm:ss ZZ').format('YYYY-MM-DD HH:mm:ss')

Alternatively, pass the data in a format that moment recognizes as listed here. In your case, simply removing the space between the time and the offset would work.

var txt = '2014-09-26 23:57:02+0530';
moment(txt).format('YYYY-MM-DD HH:mm:ss')

Upvotes: 1

Related Questions