<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>获取时区时间</title>
</head>
<body>
<script type="text/javascript">
function getCurrentTime(t) {
//t为时区参数 默认东八区北京时间
if (!t) t = 8;
const time = new Date();
const len = time.getTime();
const offset = time.getTimezoneOffset() * 60000; //本地时间与GMT时间差值
const utcTime = len + offset; //格林尼治时间
const date = new Date(utcTime + 3600000 * t); //格林尼治时间和当前时区差值
const y = date.getFullYear(),
mon = date.getMonth() + 1,
d = date.getDate(),
h = date.getHours(),
m = date.getMinutes(),
s = date.getSeconds();
//不足两位补0
function addZero(value) {
if (value < 10) return "0" + value;
else return value;
}
const result = y + "-" + addZero(mon) + "-" + addZero(d) + " " + addZero(h) + ":" + addZero(m) + ":" + addZero(s);
return result
}
//8为东八区北京时间 东区时区1~12 西区时区-1~-12
console.log("%c北京时间", "color:red;font-weight:bold;", getCurrentTime());
console.log("%c东九区-东京时间" ,"color:green;font-weight:bold;", getCurrentTime(9));
console.log("%c西九区-阿拉斯加时间" ,"color:blue;font-weight:bold;", getCurrentTime(-9));
</script>
</body>
</html>