Karan Thakkar
Karan Thakkar

Reputation: 3

UTC date convert to local timezone

I have a date in UTC format.

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

I made a 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.

My code produced this output:

Tue Oct 11 2016 10:33:00 GMT+0530 (IST)

I converted the date with an online tool to get the correct date and time.

Wednesday, October 12, 2016 10:30 AM

My code matches the online tool on time but not on date.

How can I correct my code's output, preferably using moment.js?

Upvotes: 0

Views: 686

Answers (2)

RobG
RobG

Reputation: 147403

UTC is a standard, not a format. I assume you mean your strings use a zero offset, i.e. "2016-10-12 05:03:51" is "2016-10-12 05:03:51+0000"

You are on the right track when parsing the string, but you can use UTC methods to to stop the host from adjusting the values for the system offset when creating the date.

function parseDateUTC(s){   
  var arr = s.split(/\D/);
  return new Date(Date.UTC(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]));
}

console.log(parseDateUTC('2016-10-12 05:03:51').toLocaleString());

If you want to use moment.js, you can do something like the following. It forces moment to use UTC when parsing the string, then local to write it to output:

var d = moment.utc('2016-10-12 05:03:51','YYYY-MM-DD HH:mm:ss');
console.log(d.local().format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.0/moment.js"></script>

Upvotes: 1

Rajesh
Rajesh

Reputation: 24915

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

Upvotes: 0

Related Questions