按照你的要求编写的计算时间差的Javascript程序如下(注意 date是随意写的正确的日期字符串,只是为了函数Date.parse()的需要)
<script type=text/javascript>var date="2018/07/17"
var time1 = Date.parse(date+" "+"2:32:39")
var time2 = Date.parse(date+" "+"14:12:09")
var time3=time2-time1
var hour=Math.floor(time3/1000/60/60)
var minute=Math.floor(time3/1000/60-hour*60)
var second=time3/1000-hour*60*60-minute*60
alert("时间差为"+hour+"小时"+minute+"分"+second+"秒")
</script>
运行结果
时间差为11小时39分30秒
// 计算两个时间戳相差的多少年多少月多少天
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
}