d in the code below alerts one day back if i am in US timezone, How do i fix this issue?
d = new Date("2016-05-31");
alert(d);
I am not sure why this happens if i am in India timezone it displays fine.
d in the code below alerts one day back if i am in US timezone, How do i fix this issue?
d = new Date("2016-05-31");
alert(d);
I am not sure why this happens if i am in India timezone it displays fine.
You're using an abbreviated ISO time string to initialize the date instance, so the default time zone is GMT (Z). Instead, you can use the three-argument constructor that accepts numeric year, month, and day-of-month:
var d = new Date(2016, 4, 31);
That will assume local time zone. Note that months are numbered from zero.
You can create the date differently using:
var date = new Date(2016, 4, 31);
Or, you can set the UTC hours of the date after you've created it using your current method (less preferable, given browser/regional date incompatibilities):
var date = new Date("2016-05-31");
date.setUTCHours(0);
Try this script and check the console for output to highlight the differences:
var date1 = new Date('2016-05-31');
var date2 = new Date(2016, 4, 31);
var str1 = date1.toISOString();
var str2 = date2.toISOString();
console.log('date1', date1, str1, date1.getUTCHours(), date1.toUTCString());
console.log('date2', date2, str2, date2.getUTCHours(), date2.toUTCString());
date1.setUTCHours(0);
date2.setUTCHours(0);
console.log('date1', date1, str1, date1.getUTCHours(), date1.toUTCString());
console.log('date2', date2, str2, date2.getUTCHours(), date2.toUTCString());
You may also wish to look at the Moment.js time library. Specifically, the Moment.js timezone library.