This is some code I wrote in Jan 2016 for Jonathan Berger's Time Zone Converter. Near midnight in the selected cities of "Apia" and "Pago Pago", the time was shown as the "NEXT DAY" instead of the actual two day difference. I modified his '.js' file to fix it.
Suprisingly, he didn't mind my precision, but matched me with it. When comparing days, I should have tested it for 30 and 45 minute offset time zones. In lieu of doing this, he removed the two towns nearest the international date line.
I modified ttzc.js so it displays differences of 2 days.
At first I just wanted to call getDay on fromDate and toDate, but that's no good since it returns a day from 0-6. I can't easily subtract numbers like those to get days between since if today is day 6, then tomorrow is day 0.
So I had to do this to compare the days:
- Make copies of the date objects
- Remove the hour from the copies
- Take difference of copies in milliseconds
- With days compared, write to page
I had to make a copy of the dates since I will need to modify the dates in order to compare the days between them.
var fromDay = new Date(fromDate.getTime());
var toDay = new Date(toDate.getTime());
I set the copied dates to have hour zero in order to find the number of days between the dates without worrying about the differences in hours. We don't need to worry about the zero difference in minutes.
fromDay.setHours(0);
toDay.setHours(0);
I subtracted the two dates to get the difference in days between them.
var dDay = Math.round((toDay.getTime()-fromDay.getTime())/86400000);
On the same line where I took the difference between the days:
- I converted the millisecond difference to days.
- I rounded to assure integers for indexing.
I made an array with all the right phrases. I cleared the info, defaulting to no day difference.
var dName = ['two days behind','previous day','','next day','two days ahead'];
fromSide.getView().clearTimeInfo();
If the day difference is -2, -1, 1, or 2, I updated the info with the appropriate phrase from the array.
if (dDay != 0 && dDay > -3 && dDay < 3){
toSide.getView().setTimeInfo(dName[dDay+2]);
}
If the day difference is 0, then the info stays cleared. Otherwise, the number of days is labeled in your wording.