Ashley Ashley - 3 days ago 5
Javascript Question

Convert UTC datetime string to browser based timezone in javascript

Is there a way to convert a

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

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

Answer

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');
console.log(date.toString()); 

Demo here

Comments