<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.father {
width: 500px;
margin-bottom: 20px;
border: 1px solid;
padding-left: 10px;
}
</style>
</head>
<body>
<div class="father">
<p>中国标准时间:<span id="standard1"></span></p>
<button onclick="getTime()">中国标准时间转化为标准时间</button>
<p>标准时间:<span id="standard2"></span></p>
</div>
<div class="father">
<p>标准时间:<span id="standard3">2023-01-29 17:47:43</span></p>
<button onclick="getTime2()">标准时间转化为中国标准时间</button>
<p>中国标准时间:<span id="standard4"></span></p>
<p>转化成时间戳:<span id="standard5"></span></p>
</div>
<script>
var time = new Date()
document.getElementById('standard1').innerHTML = time
/**
* Date 时间对象 创建Date对象 new Date()
* const d1 = new Date() // 获取现在的标准时间: Sun Jan 29 2023 14:58:49 GMT+0800 (中国标准时间)
* const d2 = new Date(1674975029492) // 参数是时间戳类型的
* const d3 = new Date(2023, 0, 29, 0, 0, 0) // 0表示1月,1表示2月,依此类推
* getDate() 从 Date 对象返回一个月中的某一天 (1 ~ 31)
* getDay() 从 Date 对象返回一周中的某一天 (0 ~ 6)。
* getFullYear() 从 Date 对象以四位数字返回年份。
* getHours() 返回 Date 对象的小时 (0 ~ 23)。
* getMilliseconds() 返回 Date 对象的毫秒(0 ~ 999)。
* getMonth() 从 Date 对象返回月份 (0 ~ 11)。
* getTime() 返回 1970 年 1 月 1 日至今的毫秒数
*/
// 中国标准时间 - 格式: Sun Jan 29 2023 17:54:48 GMT+0800 (中国标准时间)
// 时间戳 - 格式: 1649462400000
// 中国标准时间 => 标准时间
function getTime () {
var year = time.getFullYear()
var month = time.getMonth() + 1
var day = time.getDate()
var hour = time.getHours()
var min = time.getMinutes()
var second = time.getSeconds()
month < 10 ? month = '0' + month : month
day < 10 ? day = '0' + day : day
hour < 10 ? hour = '0' + hour : hour
min < 10 ? min = '0' + min : min
second < 10 ? second = '0' + second : second
document.getElementById('standard2').innerHTML = year + '-' + month + '-' + day + ' ' + hour + ':' + min + ':' + second
}
// 标准时间 => 中国标准时间
function getTime2 () {
const time = '2023-01-29 17:47:43'
const time1 = new Date(time)
// 转化成时间戳
const time2 = new Date(time).getTime()
document.getElementById('standard4').innerHTML = time1
document.getElementById('standard5').innerHTML = time2
}
</script>
</body>
</html>```