0

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.

ManoDestra
  • 6,325
  • 6
  • 26
  • 50
sushil bharwani
  • 29,685
  • 30
  • 94
  • 128
  • If your web is running in India, then that date represents Midnight in your time zone, but it is the previous day, some hours earlier, in more Western time zones. It is largely not recommended to instantiate a date using the string constructor due to browser incompatibility with respect to date formats. This may help you: http://stackoverflow.com/questions/439630/how-do-you-create-a-javascript-date-object-with-a-set-timezone-without-using-a-s – ManoDestra May 19 '16 at 13:17
  • Yes i understand that but what if i want to be neutral i want to show the date to user in a datepicker which was submitted by him in db. – sushil bharwani May 19 '16 at 13:19
  • You should probably just use UTC, as suggested in the article I referenced then `.setUTCHours()`. – ManoDestra May 19 '16 at 13:20
  • In which format you are getting the date from db? Is it the string given in the question? – Shrabanee May 19 '16 at 13:23
  • yes Its the string in the Question – sushil bharwani May 19 '16 at 13:44

2 Answers2

2

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
1

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.

ManoDestra
  • 6,325
  • 6
  • 26
  • 50