需要准备的材料分别有:电脑、html编辑器、浏览器。
1、首先,打开html编辑器,新建html文件,例如:index.html。
2、在index.html中的<script>标签,输入js代码:var a = 1562060142000document.body.innerText = new Date(a)。
3、浏览器运行index.html页面,此时时间被转化为年月日时分秒打印出来了。
function showTime() {var now = new Date()
var nowTime = now.toLocaleString()
var date = nowTime.substring(0,10)//截取日期
var time = nowTime.substring(10,20) //截取时间
var week = now.getDay() //星期
var hour = now.getHours() //小时
//判断星期几
var weeks = ["日","一","二","三","四","五","六"]
var getWeek = "星期" + weeks[week]
var sc
//判断是AM or PM
if(hour >= 0 && hour < 5){
sc = '凌晨'
}
else if(hour > 5 && hour <= 7){
sc = '早上'
}
else if(hour > 7 && hour <= 11){
sc = '上午'
}
else if(hour > 11 && hour <= 13){
sc = '中午'
}
else if(hour> 13 && hour <= 18){
sc = '下午'
}
else if(hour > 18 && hour <= 23){
sc = '晚上'
}
document.getElementById('time').innerHTML ="当前时间:" + date+" " + getWeek +"&nbsp"+" "+sc+" "+time
setTimeout('showTime()',1000)
}
</script>
调用方法:
<body onload="showTime()">
<div id="time"></div>
</body>
2.简洁的办法: 显示格式: 当前时间: 2010年6月1日 10:00:00 星期一
<htmtl>
<head></head>
<body>
<div id="linkweb" style=" display:inline"></div>
<script>
setInterval("document.getElementById('linkweb').innerHTML=new Date ().toLocaleString()+' 星期'+'日一二三四五六'.charAt(new Date().getDay ())",1000)
</script>
</body>
</html>
// 计算两个时间戳相差的多少年多少月多少天
calculateDiffTime() {
let startTime = '1629107469000' //2021-08-16 17:51
let endTime = '1976262719000' //2032-08-16 17:51
let flag = [1, 3, 5, 7, 8, 10, 12, 4, 6, 9, 11, 2]
let start = new Date(startTime)
let end = new Date(endTime)
let year = end.getFullYear() - start.getFullYear()
let month = end.getMonth() - start.getMonth()
let day = end.getDate() - start.getDate()
if (month <0) {
year--
month = end.getMonth() + (12 - start.getMonth())
}
if (day <0) {
month--
let index = flag.findIndex((temp) =>{
return temp === start.getMonth() + 1
})
let monthLength
if (index <= 6) {
monthLength = 31
} else if (index >6 &&index <= 10) {
monthLength = 30
} else {
monthLength = 28
}
day = end.getDate() + (monthLength - start.getDate())
}
this.result = `相差${year}年${month}月${day}天`
console.log(this.result)
}
# 计算两个时间戳相差的多少年多少月多少天多少小时多少分多少秒(另一种写法)
//计算两个时间戳相差的多少年多少月多少天多少小时多少分多少秒
calculateDiffTime (){
let startTime = '1629107469000' //2021-08-16 17:51
let endTime = '1976262719000' //2032-08-16 17:51
let runTime = parseInt((endTime - startTime) / 1000)
var year = Math.floor(runTime / 86400 / 365)
runTime = runTime % (86400 * 365)
var month = Math.floor(runTime / 86400 / 30)
runTime = runTime % (86400 * 30)
var day = Math.floor(runTime / 86400)
runTime = runTime % 86400
var hour = Math.floor(runTime / 3600)
runTime = runTime % 3600
var minute = Math.floor(runTime / 60)
runTime = runTime % 60
var second = runTime
console.log(`相差${year}年${month}月${day}天${hour}小时${minute}分${second}秒`)
return year+','+month+','+day+','+hour+','+minute+','+second
}