Advertisement
bpoole

Simple jQuery Clock with Timezone Offset Support

Oct 19th, 2016
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
jQuery 1.91 KB | None | 0 0
  1. //quick code to create one or more clocks on a site with the ability to adjust each one given a UTC offset (in seconds)
  2. //sample HTML
  3. //  <span class="clock"><!-- UTC time --></span>
  4. //  <span class="clock" data_offset="-10800"><!-- UTC-3 --></span>
  5.  
  6. $(function() {
  7.     init_clocks( );
  8. });
  9.  
  10. var clock_update_timer;
  11. var weekday = new Array(7);
  12. weekday[0]=  'Sun';
  13. weekday[1] = 'Mon';
  14. weekday[2] = 'Tues';
  15. weekday[3] = 'Wed';
  16. weekday[4] = 'Thurs';
  17. weekday[5] = 'Fri';
  18. weekday[6] = 'Sat';
  19. function init_clocks( ){
  20.     if($('.clock').length == 0){ return; }
  21.  
  22.     update_clocks( );
  23.  
  24.     //just in case
  25.     clearInterval(clock_update_timer);
  26.     clock_update_timer = setInterval(update_clocks, 1000);
  27. }
  28.  
  29. function update_clocks( ){
  30.     $('.clock').each(function( ){
  31.         offset_seconds = parseInt($(this).data('offset'));
  32.  
  33.         utc = new Date( );
  34.  
  35.         currentTime = new Date((new Date(utc.getUTCFullYear( ), utc.getUTCMonth( ), utc.getUTCDate( ), utc.getUTCHours( ), utc.getUTCMinutes( ), utc.getUTCSeconds( ))).getTime( ) + (offset_seconds * 1000));
  36.         currentHours = currentTime.getHours( );
  37.         currentMinutes = currentTime.getMinutes( );
  38.         currentSeconds = currentTime.getSeconds( );
  39.  
  40.         currentWDay = weekday[currentTime.getDay( )];
  41.  
  42.         timeOfDay = (currentHours < 12) ? 'am' : 'pm';
  43.  
  44.         currentHours = (currentHours > 12) ? currentHours - 12 : currentHours;
  45.         currentHours = (currentHours == 0) ? 12 : currentHours;
  46.  
  47.         currentHours = (currentHours < 10 ? '0' : '') + currentHours;
  48.         currentMinutes = (currentMinutes < 10 ? '0' : '') + currentMinutes;
  49.         currentSeconds = (currentSeconds < 10 ? '0' : '') + currentSeconds;
  50.  
  51.         // Compose the string for display
  52.         currentTimeString = currentWDay + ' ' + currentHours + ':' + currentMinutes + ':' + currentSeconds + ' ' + timeOfDay;
  53.  
  54.         $(this).text(currentTimeString);
  55.     });
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement