JavaScript 如何将UTC日期时间转换为本地日期时间
给定一个UTC日期,并需要使用JavaScript将其转换为本地日期时间 toLocaleString() 函数。
语法:
var theDate = new Date(Date.parse('DATE_IN_UTC'))
theDate.toLocaleString()
示例 1: 这个示例使用JavaScript将UTC日期时间转换为本地日期时间。
<body>
<h1 style="color:green;">
GeekforGeeks
</h1>
<p>
Click the button to convert
UTC date and time to local
date and time
</p>
<p>
UTC date and time:
06/14/2020 4:41:48 PM
</p>
<button onclick="myGeeks()">
Try it
</button>
<p id="demo"></p>
<script>
function myGeeks() {
var theDate = new Date(Date.parse(
'06/14/2020 4:41:48 PM UTC'));
document.getElementById("demo")
.innerHTML = "Local date Time: "
+ theDate.toLocaleString();
}
</script>
</body>
输出:
示例2: 此示例使用JavaScript将今天的UTC日期时间转换为本地日期时间。
<body>
<h1 style="color:green;">
GeekforGeeks
</h1>
<p>
Click the button to convert
UTC date and time to local
date and time
</p>
<p id="UTC_DATE">
UTC date and time:
06/14/2020 4:41:48 PM
</p>
<button onclick="myGeeks()">
Try it
</button>
<p id="demo"></p>
<script>
var theDate = new Date().toUTCString();
document.getElementById("UTC_DATE").innerHTML = "UTC date and time: "
+ theDate
function myGeeks() {
var theDate = new Date().toLocaleString();
document.getElementById("demo")
.innerHTML = "Local date Time: "
+ theDate.toLocaleString();
}
</script>
</body>
输出: