skip to Main Content

I can make a clock appearing with correct time based on $time_zone1. So far so good. The only problem is that the clock does not update every second – or at all. I have struggled with solution where time is created in javascript (instead of using $current_time_formatted), but that did not work as javascript always created clock using my local time instead of the time set in $time_zone1.

Also, I want to be able to change ‘America/New_York’ to other time zone. So, in PHP, I will fetch a certain time zone, say that now $time_zone=’Europe/London’. So, somehow I have to tell javascript to create clock for ‘Europe/London’, instead of ‘America/New_York’.
That is,

$time_zone1 = new DateTime('now', new DateTimeZone($time_zone))
<?php
// Create a DateTime object for the current time
// 'America/New_York', 'Europe/London', 'Asia/Tokyo'
$time_zone1 = new DateTime('now', new DateTimeZone('America/New_York'));

// Format the current time
$current_time_formatted = $time_zone1->format('H:i:s');
?>

<!-- Display the clock -->
<div id="clock"><?php echo $current_time_formatted; ?> America/New_York</div>

<!-- JavaScript for updating the clock -->
<script>
function updateTime() {
    // Get the clock element
    var clock = document.getElementById('clock');
    
    // Update the clock display using the PHP variable directly
    clock.innerHTML = '<?php echo $current_time_formatted; ?>' + ' America/New_York';
}

// Update the clock every second
setInterval(updateTime, 1000);
</script>

2

Answers


  1. You can make the time in JavaScript for a specific timezone using Intl.DateTimeFormat

    <?php
    $time_zone = "America/New_York";
    ?>
    
    <!-- Display the clock -->
    <div id="clock"> <?php echo $time_zone; ?></div>
    
    <!-- JavaScript for updating the clock -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
    <script>
        $(document).ready(function() {
            function updateTime() {
                let options = {
                    timeZone: "<?php echo $time_zone; ?>",
                    timeStyle: 'medium',
                };
    
                formatter = new Intl.DateTimeFormat([], options);
    
                // Get the clock element
                var clock = document.getElementById('clock');
    
                // Update the clock display using the PHP variable directly
                clock.innerHTML = formatter.format(new Date()) + ' <?php echo $time_zone; ?>';
            }
    
            // Update the clock every second
            setInterval(updateTime, 1000);
        })
    </script>
    
    Login or Signup to reply.
  2. You could extend the idea of a simple clock using a simple custom-component so that all the clock functionality is self-contained and easily customisable using PHP to write the necessary timezone to the HTML element.

    The custom-component class uses the Intl.DateTimeFormat to render the time in your selected format, again customisable by editing the dataset attributes for the component.

    class SimpleClock extends HTMLElement{
        static get observedAttributes(){ 
          return [
            'data-timeZone',
            'data-timeStyle'
          ]
        };
    
        constructor(){
          const self=super();
          this.shadow=this.attachShadow( { mode:'open' } );
        };
    
        create(){
          return new Promise( ( resolve, reject )=>{
            let style=document.createElement('style');
                style.textContent=`
                div{
                  width: 150px;
                  border: 2px solid grey;
                  border-radius: 0.5rem;
                  padding: 0.5rem;
                  margin: 0.5rem 0.25rem;
                  
                  display: flex;
                  flex-direction: column;
                  justify-content: center;
                  align-items: center;
                  
                  color: grey;
                  background: whitesmoke;
                  box-shadow: 0 0 0.5rem silver;
                  font-family: monospace;
                  font-size: 0.95rem;
                }
                
                div:after{
                  content: attr(data-timezone);
                  color: black;
                  font-size: smaller;
                }
                
                div:before{
                  content:attr(data-time)
                }`;
            this.shadow.appendChild( style );
            this.node=this.shadow.appendChild( document.createElement('div') );
            this.node.dataset.timezone=this.dataset.timezone;
            resolve( true )
          });
        };
    
        render(){
          return new Promise( ( resolve, reject )=>{
            const IntlDateFormatter=function( date, args={} ){
              let options=Object.assign( 
                { timeStyle:'short', timeZone:'Europe/London' }, 
                args 
              );
              return new Intl.DateTimeFormat( [], options ).format( date )
            };
            
            let args={
               timeZone:this.dataset.timezone,
               timeStyle:this.dataset.timestyle
            }
            
            this.node.dataset.time=IntlDateFormatter( new Date(), args );
            resolve( true );
          });
        };
    
        connectedCallback(){
          this.create()
            .then( bool=>setInterval( this.render.bind( this ), 1000 ) )
            .catch( console.info )
        };
      }
      
      window.customElements.define( 'simple-clock', SimpleClock );
    simple-clock{
      display:inline-block;
      margin:1rem 0.5rem;
    }
    <simple-clock data-timeZone='Europe/London' data-timeStyle='long'></simple-clock>
    <simple-clock data-timeZone='Europe/Paris' data-timeStyle='long'></simple-clock>
    <simple-clock data-timeZone='Europe/Dublin' data-timeStyle='medium'></simple-clock>
    <simple-clock data-timeZone='America/New_York' data-timeStyle='medium'></simple-clock>
    <!--
    
    <simple-clock data-timeZone='<?php echo $time_zone1;?>' data-timeStyle='medium'></simple-clock>
    -->
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search