/**
 * This snippet of JavaScript returns the current time
 * in a particular time zone when loaded in a client's web browser.
 * I created this so that people back home in the U.S. would know what time
 * it was in India when reading my India blog.
 * 
 * Michael Bolin
 * http://www.bolinfest.com/india04/
 *
 * KNOWN ISSUES:
 *
 * (1) This code has not been tested to see if it correctly handles
 *     daylight saving time.
 * (2) The timezone of the Date returned by getForeignDate() will not
 *     be correct: see doc comment for getForeignDate() for details.
 *
 * This code may be copied and used freely so long as
 * the doc comments remain unchanged.
 */

/**
 * Sample usage:
 *
 * (1) Set DESIRED_OFFSET to the appropriate GMT offset. For example,
 *     if you wanted to get the time in India (which is GMT +05:30),
 *     you should have:
 *
 *   var DESIRED_OFFSET = 5.5;
 *
 * (2) Include the following inside the <head> tag:
 *
 *   <script src="foreign_time.js"></script>
 *
 * (3) Put the following somewhere in the <body> tag to display the time:
 *
 *   <script>
 *   <!--
 *     fdate = getForeignDate();
 *     hour = fdate.getHours();
 *     minute = fdate.getMinutes();
 *     ampm = (hour < 12) ? "AM" : "PM";
 *     if (hour == 0) {
 *       hour = 12;
 *     } else if (hour > 12) {
 *       hour -= 12;
 *     }
 *     if (minute < 10) {
 *       minute = "0" + minute;
 *     }
 *     output = "The time in India is now " +
 *              hour + ":" + minute + ampm;
 *     document.writeln(output);
 *   // -->
 *   </script> 
 *
 */

/** The offset of the time (in hours) that getForeignDate() returns */
var DESIRED_OFFSET = 5.5; // e.g., use 5.5 for India (GMT +05:30)

/** the number of milliseconds per hour: a constant */
var MILLIS_PER_HOUR = 1000 * 60 * 60;

/**
 * returns a JavaScript Date object
 * such that the time and date of the Date object will appear
 * to be that of the timezone that you wish to display;
 * however, the timezone of the Date returned will be that
 * of the client's local time.
 *
 * A Date object is returned so that you can pass it into whatever
 * existing Date parsing code that you use, so be aware that
 * if you display the timezone of this Date object, it will most
 * likely be incorrect.
 */
function getForeignDate() {
  now = new Date();
  minutes = now.getTimezoneOffset();
  hours = minutes / -60;
  hoursDifference = hours - DESIRED_OFFSET;
  millisDifference = MILLIS_PER_HOUR * hoursDifference;
  millisNow = now.getTime() - millisDifference;
  dateInForeignPlace = new Date(millisNow);
  return dateInForeignPlace;
}

