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

2

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

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 Yeah, You can check my edited answer with moment.
It uses moment but.
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 here.
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.

1 Comment

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 here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.