1

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

Ashley
  • 441
  • 2
  • 8
  • 27
  • You can check for `date.toLocaleString()` but I'd suggest using `moment`. – Rajesh Nov 30 '16 at 05:39
  • This might help: http://stackoverflow.com/questions/8469436/how-format-javascript-date-with-regard-to-the-browser-culture – Rajesh Nov 30 '16 at 05:40

2 Answers2

4

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

Satyam Koyani
  • 4,236
  • 2
  • 22
  • 48
  • I have edited the question. Can we get the datetime string in the same format based on timezone without using other third-party libraries like moment ? – Ashley Nov 30 '16 at 05:47
  • @Ashley Yeah, You can check my edited answer with moment. – Satyam Koyani Nov 30 '16 at 05:49
  • It uses moment but. – Ashley Nov 30 '16 at 05:50
  • 1
    Thanks for the answer ! Also using date.toLocaleString() gives the datetime string in locale browser culture like 11/30/2016 8:35:24 AM. [Demo](https://jsfiddle.net/kvtv4unq/1/) here. – Ashley Nov 30 '16 at 06:45
2

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.

abhishekkannojia
  • 2,796
  • 23
  • 32
  • 1
    Thanks for the answer ! Also using date.toLocaleString() gives the datetime string in locale browser culture like 11/30/2016 8:35:24 AM. [Demo](https://jsfiddle.net/kvtv4unq/1/) here. – Ashley Nov 30 '16 at 06:47