-1

Get time based on selected timezone :

I have a JS function that takes a time zone as an argument and returns the current time in that time zone.

function worldClock(zone) {
    var time = new Date()
    var gmtMS = time.getTime() + (time.getTimezoneOffset() * 60000)
    var gmtTime = new Date(gmtMS)

    var hr = gmtTime.getHours() + zone
    var min = gmtTime.getMinutes()
    var sec = gmtTime.getSeconds()

    if (hr < 10){
    hr = "0" + hr
    }
    if (min < 10){
    min = "0" + min
    }
    if (sec < 10){
    sec = "0" + sec
    }
    return hr + ":" + min + ":" + sec;
};

I also have a dropdown list with a list of cities and their time zone as a value.

 <select name="city">
        <option value="-4">Toronto</option>
        <option value="2">Stokholm</option>
        <option value="-5">New-York</option>
      </select>

I need the worldClock () function to be called when a certain city is selected; pass the value from the dropdown list as an argument and display the resulting value and city name: Toronto: 04:52:16; How can this be implemented?

Dinesh Ghule
  • 3,277
  • 4
  • 22
  • 38
Mikhail Kostiuchenko
  • 6,301
  • 4
  • 11
  • 23
  • 1
    add an event listener on the select, when it changes. get the selected option and pass the value to the function – lois6b Oct 25 '18 at 08:54
  • 1
    Shortest simplest way: ` – ADyson Oct 25 '18 at 08:54

1 Answers1

0

Add Onchange event:

function worldClock(zone) {
    var time = new Date()
    var gmtMS = time.getTime() + (time.getTimezoneOffset() * 60000)
    var gmtTime = new Date(gmtMS)

    var hr = gmtTime.getHours() + zone
    var min = gmtTime.getMinutes()
    var sec = gmtTime.getSeconds()

    if (hr < 10){
    hr = "0" + hr
    }
    if (min < 10){
    min = "0" + min
    }
    if (sec < 10){
    sec = "0" + sec
    }
    var output= hr + ":" + min + ":" + sec;
    console.log(output);
    return output;
};
 <select name="city" onchange="worldClock(this.value);">
        <option value="-4">Toronto</option>
        <option value="2">Stokholm</option>
        <option value="-5">New-York</option>
      </select>
Dinesh Ghule
  • 3,277
  • 4
  • 22
  • 38