City World Clock - based on Timezone

This javascript code snippet allows you to display the time of a city, selected from a drop-down. It also loads the current time and location as the default time and location (based on computer’s timezone and entry in dropdown list). The script is mostly similar to the previous post.

        Here also we have 2 divs for displaying time and date, and a select drop-down for selecting city. We are also using the ‘calculateZoneTime()’ function for calculating time. Also we have slightly modified ‘returnFormattedDate()’ and ‘returnFormattedTime()’ functions for formatting date and time respectively. The time is updated every second using the ‘init()’ function. The ‘init()’ function calls the ‘calculateZoneTime()’ function and repeats itself using the setInterval function.

        An additional function is ‘calculateDefaultTimeZone()’ which is used for calculating the computer’s current timezone and setting the html select to that particular timezone on page load.
function calculateDefaultTimeZone() {

      var newDate = new Date();
      // finding current timezone – received in decimal format
      var timeOffset = (newDate.getTimezoneOffset()/60) * (-1);
      var timeZone1 = document.getElementById('selectTZ1');
      // converting decimal format to “hh:mm” format
      var formattedOffset = formatTimeOffset(timeOffset);
  
      if (timeZone1)  {
            // finding the current timezone in select drop-down
            for (var i = 0; i < timeZone1.options.length; i++) {
                  if (timeZone1.options[i].value == formattedOffset) {
                        timeZone1.selectedIndex = i;
                         break;
                  }
            }
      }
}
        The ‘formatTimeOffset()’ function converts the calculated current time zone from a decimal format to a  “+/-hh:mm”  format. Here is the function code:
function formatTimeOffset(value) {
      var hours = parseInt(value);
      value -= parseInt(value);
      value *= 60;
      var mins = Math.abs(parseInt(value));
      var display_hours = hours; 
      var display_mins = (mins < 10) ? ("0" + mins) : mins;
      timeZoneString = display_hours + ":" + display_mins;
      return timeZoneString;
}
Please enter your valuable comments and suggestions.
You can find the entire code along with html from below.
<html>
<head>
<title> City clock </title>
<style>
  body {
      text-align : center;
  }
  select {
      width: 130px;
  }
  .mainDiv {
      width : 170px;
      height : 170px;
      background-color : #eeeeee; 
  }
  .subDiv {
      width : 130px;
  }
  #timeText1 {
      font-size: 17px;
      font-weight: bold;
      font-family: Trebuchet MS, Lucida Sans Unicode, Arial, sans-serif;
  }
  #dayText1 {
      font-size: 13px;
      font-weight: bold;
      font-family: Trebuchet MS, Lucida Sans Unicode, Arial, sans-serif;
  }
</style>
<script type="text/javascript" language="javascript">
/** Initialises the Clock and updates it every second. **/
function init() {
    try {
        clearInterval(myInterval);
    } catch(err){}
    calculateZoneTime(document.getElementById("selectTZ1").value,1);
    myInterval = setInterval("init()",1000);
}
/** Calculates the default time zone based on System Date. **/
function calculateDefaultTimeZone() {
    var newDate = new Date();
    var timeOffset = (newDate.getTimezoneOffset()/60) * (-1);
    var timeZone1 = document.getElementById('selectTZ1');
    var formattedOffset = formatTimeOffset(timeOffset);
    if (timeZone1) {
        for (var i = 0; i < timeZone1.options.length; i++) {
            if (timeZone1.options[i].value == formattedOffset) {
                timeZone1.selectedIndex = i;
                break;
            }
        }
    }
}
/** Format the time based upon the time-zone. **/
function formatTimeOffset(value) {
    var hours = parseInt(value);
    var mins = Math.abs((value - parseInt(value)) * 60);
    var display_mins = (mins < 10) ? ("0" + mins) : mins;
    var timeZoneString = hours + ":" + display_mins;
    return timeZoneString;
}
/** Populates the Time and Date based upon the current time-zone. **/
function calculateZoneTime(TimeZoneOffset,num) {
    var lDate = new Date();
    try {
        var timeArray = TimeZoneOffset.split(":");
        var hrs = parseInt(timeArray[0]);
        var mins = parseInt(timeArray[1])/60;
    } catch(err){}
    var ZoneOffset = (hrs > 0) ? (hrs + mins) : (hrs - mins);
    var ms = lDate.getTime() + (lDate.getTimezoneOffset() * 60000) + ZoneOffset * 3600000;
    var time =new Date(ms);
    var dayText = returnFormattedDate(time);
    var timeText =returnFormattedTime(time);
    document.getElementById("timeText"+num).innerHTML=timeText;
    document.getElementById("dayText"+num).innerHTML=dayText;
}
/** Returns the Time in HH:mm:ss PM/AM format. **/
function returnFormattedTime(dateObject) {
    var hrs = dateObject.getHours();
    var mins = dateObject.getMinutes();
    var seconds = dateObject.getSeconds();
    var meridian = "am";
    if (hrs == 12) {
        meridian = "pm";
    } else if(hrs == 0) {
        meridian = "am";
        hrs = 12;
    } else if(hrs > 12) {
        meridian = "pm";
        hrs = hrs - 12;
    }
    display_hours = (hrs < 10) ? ("0" + hrs) : hrs;
    display_mins = (mins < 10) ? ("0" + mins) : mins;
    display_seconds = (seconds < 10) ? ("0" + seconds) : seconds;
    return ( display_hours + " : " + display_mins +" : " + display_seconds +"" + meridian);
}
/** Returns the Date in Day,dd:MMM:yyyy format **/
function returnFormattedDate(dateObject) {
    var tdate = dateObject.getDate();
    var tmnth = dateObject.getMonth()
    var tyear = dateObject.getYear() ;
    var tday= dateObject.getDay();
    var mnthName = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
    var dayName = new Array("sun","Mon","Tue","Wed","Thu","Fri","Sat");
    return ( dayName[tday] + " , " + tdate + " " + mnthName[tmnth] + " " + tyear ); 
}
</script> 
</head>
<body onload="calculateDefaultTimeZone();init();">
<div align="center" class="mainDiv">
<h3><u><i> CITY CLOCK </i></u></h3>
<div id="div1" class="subdiv">
    <div name="timeText1" id="timeText1"></div><br/>
    <div name="dayText1" id="dayText1"></div><br/>
    <select name='selectTZ1' id='selectTZ1'>
        <option value='4:00'>Abu Dhabi</option>
        <option value='9:30'>Adelaide</option>
        <option value='1:00'>Amsterdam</option>
        <option value='2:00'>Athens</option>
        <option value='3:00'>Baghdad</option>
        <option value='7:00'>Bangkok</option>
        <option value='8:00'>Beijing</option>
        <option value='1:00'>Berlin</option>
        <option value='-3:00'>Brasilia</option>
        <option value='-3:00'>Beunos Aires</option>
        <option value='5:30'>Bangalore</option>
        <option value='1:00'>Budapest</option>
        <option value='1:00'>Brussels</option>
        <option value='2:00'>Cairo</option>
        <option value='2:00'>Cape Town</option>
        <option value='10:00'>Canberra</option>
        <option value='-6:00'>Chicago</option>
        <option value='1:00'>Copenhagen</option>
        <option value='5:30'>Colombo</option>
        <option value='5:30'>Chennai</option>
        <option value='3:00'>Doha</option>
        <option value='-6:00'>Dallas</option>
        <option value='3:00'>Dar es Salaam</option>
        <option value='6:00'>Dhaka</option>
        <option value='4:00'>Dubai</option>
        <option value='0:00'>Greenwich</option>
        <option value='2:00'>Harare</option>
        <option value='-5:00'>Havana</option>
        <option value='2:00'>Helsinki</option>
        <option value='8:00'>HongKong</option>
        <option value='5:00'>Islamabad</option>
        <option value='2:00'>Istanbul</option>
        <option value='7:00'>Jakarta</option>
        <option value='2:00'>Jerusalem</option>
        <option value='4:30'>Kabul</option>
        <option value='5:45'>Kathmandu</option>
        <option value='8:00'>Kuala lampur</option>
        <option value='5:00'>Karachi</option>
        <option value='1:00'>Lagos</option>
        <option value='0:00'>London</option>
        <option value='-8:00'>Los Angeles</option>
        <option value='5:30'>Mumbai</option>
        <option value='1:00'>Madrid</option>
        <option value='8:00'>Manila</option>
        <option value='-6:00'>Mexico city</option>
        <option value='3:00'>Moscow</option>
        <option value='4:00'>Muscat</option>
        <option value='3:00'>Nairobi</option>
        <option value='5:30'>New Delhi</option>
        <option value='-5:00'>New York</option>
        <option value='1:00'>Oslo</option>
        <option value='1:00'>Paris</option>
        <option value='8:00'>Perth</option>
        <option value='-7:00'>Phoenix</option>
        <option value='9:00'>Pyongyang</option>
        <option value='-3:00'>Rio de Janeiro</option>
        <option value='3:00'>Riyadh</option>
        <option value='1:00'>Rome</option>
        <option value='9:00'>Seoul</option>
        <option value='8:00'>Singapore</option>
        <option value='1:00'>Stockholm</option>
        <option value='10:00'>Sydney</option>
        <option value='8:00'>Taipei</option>
        <option value='3:30'>Tehran</option>
        <option value='9:00'>Tokyo</option>
        <option value='-5:00'>Toronto</option>
        <option value='1:00'>Vienna</option>
        <option value='1:00'>Vatican city</option>
        <option value='-5:00'>Washington DC</option>
        <option value='12:00'>Wellington</option>
        <option value='6:30'>Yangon</option>
    </select>
</div>
</div>
</body>
</html>

World Clock - based on Timezone

This javascript code allows you to display the time based on the user’s timezone. The script makes use of the inbuilt javascript ‘Date’ object and its functions. The clock displays time in the default 12 hour format, that can be changed to a 24 hours using a radio button. Also we are displaying the current day and date. The user can also change the timezone using a select box, and thus can view the current time in different timezones.

        First lets have a look at the form. The form consists of two div elements, one for displaying time and the other for displaying day and date. There is a select element (selectTZ) which consists of all time-zones.
<div name="timeText" id="timeText"></div>
<div name="dayText" id="dayText"></div>
<select name='selectTZ' id='selectTZ'>
    <option value='0'>Select your Timezone</option>
    <option value='-12:00'>(-12:00) International Date Line West</option>
    <option value='-11:00'>(-11:00) Midway Island, Samoa</option>
          ……………….
</select>
        Now lets start with the javascript code. First we have to retrieve the current date and time. The following line of code do this.
// create new date object
  var time =  new Date();
  // get the formatted date value 
  var dayText = returnFormattedDate(time);
  // get the formatted time value (hh:mm:ss or hh:mm:ss pm/am))
  var timeText =  returnFormattedTime(time);
  // passing formatted value to divs
  document.getElementById("timeText").innerText=timeText;     
  document.getElementById("dayText").innerText=dayText;
        The ‘returnFormattedDate()’ and ‘returnFormattedTime()’ functions return the date and time respectively in a specific format. ‘returnFormattedDate()’ returns date in “Monday, 01 January 2010” format. Whereas, ‘returnFormattedTime()’ returns time in any of the two formats, “23:45:06” or “11:45:06 pm”.

       The below function retrieves the current date and time based upon the selected time zone and places the formatted date and time on to the respective div elements.
function calculateZoneTime(SelectTimeZone) {
    // if timezone not selected
    if(SelectTimeZone=='0') {
        document.getElementById("timeText").innerText="00 : 00 : 00";
        document.getElementById("dayText").innerText= "please select a timezone";
        return true; 
    }
    // get current date object
    var zDate = new Date();
    //  retrieve offset of the selected timezone in decimal format 
    var ZoneOffset = retrieveOffset(SelectTimeZone);
    // adding the time difference to current time (in milliseconds)
    var ms = zDate.getTime() + (zDate.getTimezoneOffset() * 60000) + ZoneOffset * 3600000;
    // creating a date object using the calculated zone time
    var time =  new Date(ms);
    var dayText = returnFormattedDate(time);
    var timeText =  returnFormattedTime(time);
    document.getElementById("timeText").innerText=timeText;
    document.getElementById("dayText").innerText=dayText;
}
         Here the function parameter ‘SelectTimeZone’ is the value of the time-zone that is selected in the ‘selectTZ’ select. The ‘retieveOffset()’ function converts the parameter value from the “4:30” format to a “4.5” format, so that it can be used for date calculations. This offset is then added to the current time, to get the time-zone specific time.

        The code for ‘retieveOffset()’ is as follows:
function retrieveOffset(TimeZoneOffset) {
      try {
         // calculating the whole and decimal part of the offset 
         var timeArray = TimeZoneOffset.split(":");
         var hrs = parseInt(timeArray[0]);
         var mins = parseInt(timeArray[1])/60; 
      } catch(err){
         alert("error"); 
      }
      // adding or deleting the decimal part and whole part
      var offset = (hrs > 0) ? (hrs + mins) : (hrs - mins);
      return offset;  
}
        Now we have to update the time every second. For this we have a ‘init()’ function. The function calls the ‘calculateZoneTime()’ function and repeats itself using the setInterval function.
function init() {
     try {
             // try to clear any interval previously set
              clearInterval(myInterval);
     } catch(err){}
     // calculate time based on select value
     calculateZoneTime(document.getElementById("selectTZ").value) ;
     // repeat the init function each sec (1000ms = 1 sec)
     myInterval = setInterval("init()",1000);    
}
        This sums up the article. Hope this helps. This post is open for your queries and suggestions.
You can find the code (with HTML) in its entirety here. Also you can find an advanced version of the script that loads the current time zone as default on the clock, here.

Set as Homepage, Bookmark a page

The following javascript code snippet allows a user to add your page as homepage, and to bookmark (favorite) your page.

The following javascript function code allows you to add the current address location as the Homepage of your browser.
function setHome(){
      document.body.style.behavior='url(#default#homepage)';
      document.body.setHomePage(window.location.href);
}
The following javascript function code adds the current address location to your browser’s Bookmarks list, and the document title is set as the title (name) of the Bookmark.
function setBookmark() {
      var title = document.title;
      var address =  window.location.href;
      if(window.sidebar) {
            window.sidebar.addPanel(title,address);
      } else if(window.external) {
            window.external.AddFavorite(address,title);
      } else if(window.opera && window.print) { 
            var elem = document.createElement('a');
            elem.setAttribute('href',address);
            elem.setAttribute('title',title);
            elem.setAttribute('rel','sidebar');
            elem.click();
      }
}
The problem with the above codes is that the ‘Homepage’ code works only in Internet Explorer, and the ‘Bookmark’ code is somewhat erry in Firefox (bookmarked page opens in sidebar).
But there is another option available though not javascript. The addthis site provides you with a custom button that can be added to your site/blog, that not only allows to bookmark your page but also provides you with data related to how and where the content is being shared.
Related Posts Plugin for WordPress, Blogger...
 

Copyright © 2012 | ScriptSplash | Powered by Blogger Templates