如何使用下拉菜单或按钮(12/24小时)转换世界时钟格式?

时间:2017-11-09 01:14:37

标签: javascript jquery html

如何使用下拉菜单更改下面脚本结果的时间格式?感谢。

function show()
{
    var time=new Date()
	document.write("London " + time.toLocaleTimeString("en-US", { timeZone: "Europe/London", hour: "2-digit", minute:"2-digit" })+ "<br>");
	document.write("Paris " + time.toLocaleTimeString("en-US", { timeZone: "Europe/Paris", hour: "2-digit", minute:"2-digit" })+ "<br>");
    document.write("Tokyo " + time.toLocaleTimeString("en-US", { timeZone: "Asia/Tokyo", hour: "2-digit", minute:"2-digit" }));
}

show();
//Output
// London : time
// Paris : time
// Tokyo : time
<p>Format : 
  <select name="select" id="select">
    <option value="12">AM/PM</option>
    <option value="24">24 Hours</option>
  </select>
</p>

1 个答案:

答案 0 :(得分:0)

选择hour12: false,选项后,您可以将24 Hours添加到现有代码中。如下所示,检查更改的else条件。

function show(format) {
    var time = new Date();
    var str = "";

    if (format === "12") {
        str += "London " + time.toLocaleTimeString("en-US", { timeZone: "Europe/London", hour: "2-digit", minute: "2-digit" }) + "<br>";
        str += "Paris " + time.toLocaleTimeString("en-US", { timeZone: "Europe/Paris", hour: "2-digit", minute: "2-digit" }) + "<br>";
        str += "Tokyo " + time.toLocaleTimeString("en-US", { timeZone: "Asia/Tokyo", hour: "2-digit", minute: "2-digit" });
    }
    else {
        str += "London " + time.toLocaleTimeString("en-US", { timeZone: "Europe/London", hour12: false, hour: "2-digit", minute: "2-digit" }) + "<br>";
        str += "Paris " + time.toLocaleTimeString("en-US", { timeZone: "Europe/Paris", hour12: false, hour: "2-digit", minute: "2-digit" }) + "<br>";
        str += "Tokyo " + time.toLocaleTimeString("en-US", { timeZone: "Asia/Tokyo", hour12: false, hour: "2-digit", minute: "2-digit" });
    }

    document.getElementById("displayTime").innerHTML = str;
}

window.onload = function() { show("12") };
<p>Format :
    <select name="select" id="select" onchange="show(this.value)">
        <option value="12">AM/PM</option>
        <option value="24">24 Hours</option>
    </select>
</p>

<div id="displayTime"></div>