Ashley
Ashley

Reputation: 491

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

Upvotes: 1

Views: 1910

Answers (2)

Satyam Koyani
Satyam Koyani

Reputation: 4274

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

Upvotes: 4

abhishekkannojia
abhishekkannojia

Reputation: 2856

You could do something like this.

var dp = "11/30/2016 3:05:24 AM".split(/[/: ]/);
var dateLocale = new Date(Date.UTC(dp[2], dp[0]-1, dp[1], (dp[3]%12 + (dp[6]=='PM' ? 12 : 0)), dp[4], dp[5]));
console.log(dateLocale.toString());

Split the dates in components and pass the individual parts in Date.UTC function which returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. See Date.UTC

Create a new date object passing this value and it will return the date in local timezone.

Upvotes: 2

Related Questions