Finisher001
Finisher001

Reputation: 455

Convert UTC time to provided Timezone, must not depend on browser timezone

This kind of question is asked before but I have little tricky situation. I have a datetime that's in UTC. I want to convert it specific timezone whatever we pass. Currently i am using moment-timezone library. What happens with it is, it considers the provided time in browser's timezone and then try to convert it in provided timezone. I want to make provided time to be considered in UTC.

js code :

var datetime = '2015/04/10 15:35:00';
datetime = moment(datetime).format('YYYY-MM-DD HH:mm:ss');
datetime = moment.utc(datetime);
return moment(datetime).tz(siteTimeZone).format('YYYY-MM-DD HH:mm:ss');

i have also tried by directly applying utc like:

var datetime = '2015/04/10 15:35:00';
datetime = moment.utc(datetime).format('YYYY-MM-DD HH:mm:ss');
return moment(datetime).tz(siteTimeZone).format('YYYY-MM-DD HH:mm:ss');

but none of them work as expected. May i am not clear about how moment-timezone is working.

Please help.

Thanks!

Upvotes: 0

Views: 1006

Answers (2)

Parkash Kumar
Parkash Kumar

Reputation: 4730

Take your string in Date object, then get UTC string from it using datetime.toUTCString() and finally set timeZone & format, as following:

Following is the tested code:

var datetime = new Date('2015/04/10 15:35:00');
datetime = datetime.toUTCString();
datetime = moment(new Date(datetime)).tz(siteTimeZone).format('YYYY-MM-DD HH:mm:ss');

DEMO

Upvotes: 0

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241920

Just parse as utc before converting to the time zone.

var datetime = '2015/04/10 15:35:00';

return moment.utc(datetime,'YYYY/MM/DD HH:mm:ss')
             .tz(siteTimeZone)
             .format('YYYY-MM-DD HH:mm:ss');

Note also that I provided a format string while parsing, which matched the format of the value being passed in. This is a good practice, and will prevent moment from generating a warning on the console.

Upvotes: 2

Related Questions