Javascript Date Timezone Converter

Introduction

The World Time Converter lets you calculate the time in different countries:

View in separate window

  <!DOCTYPE html> 
  <html lang="en"> 
  <body> 
      <div>Local Time is <span id="spanLocalTime"></span></div> 
      <div id="divCityTime"></div> 
    <form name="form1"> 
        <select size="5" name="lstCity"> 
            <option value="60" selected>Berlin 
            <option value="330">Bombay 
            <option value="0">London 
            <option value="180">Moscow 
            <option value="-300">New York 
            <option value="60">Paris 
            <option value="-480">San Francisco 
            <option value="600">Sydney 
        </select> 
        <p> 
            <input type="checkbox" id="chkDst" name="chkDst" /> 

            <label for="chkDst">Adjust city time for Daylight Savings</label> 
        </p> 
    </form> 

    <script> 
        let myForm = document.form1; 

        function updateTimeZone() { 
            let lstCity = myForm.lstCity; 
            let selectedOption = lstCity .options[lstCity .selectedIndex]; 
            let offset = selectedOption.value; 
            let selectedCity = selectedOption.text; 

            let dstAdjust = 0; //  w w  w. j  ava2s  .com

            if (myForm.chkDst.checked) { 
                dstAdjust = 60; 
            } 

            updateOutput(selectedCity, offset, dstAdjust); 
        } 

        function updateOutput(selectedCity, offset, dstAdjust) { 
            let now = new Date(); 

            document.getElementById("spanLocalTime").innerHTML = now.toLocaleString(); 

            now .setMinutes(now .getMinutes() + now .getTimezoneOffset() + parseInt(offset, 10) + dstAdjust); 

            let resultsText = selectedCity + " time is " + now.toLocaleString(); 

            document.getElementById("divCityTime").innerHTML = resultsText; 
        } 
        myForm.lstCity .addEventListener("change", updateTimeZone); 
        myForm.chkDst.addEventListener("click", updateTimeZone); 

        updateTimeZone(); 
    </script> 
</body> 
</html> 



PreviousNext

Related