Karan Thakkar Karan Thakkar - 10 days ago 4x
Javascript Question

UTC date convert to local timezone

I am got date in below format.

"2016-10-12 05:03:51"

Its UTC format date.

Then i made one function to convert UTC date to my local time.

function FormatDate(date)
var arr = date.split(/[- :T]/), // from your example var date = "2012-11-14T06:57:36+0000";
date = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], 00);

var newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);

var offset = date.getTimezoneOffset() / 60;

var hours = date.getHours();

newDate.setHours(hours - offset);

return newDate;

My Local timezone is GMT +0530

I tried to convert this date through online tool. So i received correct date and time

e.g Wednesday, October 12, 2016 10:30 AM

when i tried with above code i received
Tue Oct 11 2016 10:33:00 GMT+0530 (IST)

So date is not exactly matched but time looks good.

Can someone please solve my problem?
If you know how to fix this issue with help of moment.js, it will be more helpful.



Since you have tagged moment, I'm assuming you are using moment.

In such cases, you should keep your approach consistent and not mix moment and date object.

var dateStr = '2016-10-12 05:03:51';
var timeZone = "+0530";
var date = moment.utc(dateStr).utcOffset(dateStr + timeZone)