Ashley Ashley - 1 year ago 84
Javascript Question

Convert UTC datetime string to browser based timezone in javascript

Is there a way to convert a

string of the format "11/30/2016 3:05:24 AM" to browser based timezone(say
) in javascript without using third-party libraries/scripts like moment.js ?

Example - If the timezone is
(Indian Standard Time) which is 5 hours and 30 minutes ahead of
the output should be 11/30/2016 8:35:24 AM

Answer Source

It would be best if you use moment.

var localTimeInUTC  = moment.utc('11/30/2016 3:05:24 AM','MM/DD/YYYY HH:mm:ss A').toDate();
localTime = moment(localTimeInUTC).format('YYYY-MM-DD HH:mm:ss A');
console.log(localTime); // It will be in your browser timezone

in simple with moment.

moment.utc(utcDateTime, utcDateTimeFormat).local().format(specifiedFormat)

Okay Now you cleared that you want to do without third party libraries then also it is possible.

  1. Take local timezone offset
  2. create date object from your UTC string
  3. Add your local timezone offset into that

or Simple way without thirdparty library

var dateStr = '11/30/2016 3:05:24 AM';
var date = new Date(dateStr + ' UTC');

Demo here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download