<!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>
</head>
<body>
</body>
<script>
//1.得到当前的时间(年月日时分秒)
function getNowTime (){
const date_ = new Date()
let year = date_.getFullYear()
let month = date_.getMonth() + 1
let day = date_.getDate()
if (month < 10) month = '0' + month
if (day < 10) day = '0' + day
let hours = date_.getHours()
let mins = date_.getMinutes()
let secs = date_.getSeconds()
let msecs = date_.getMilliseconds()
if (hours < 10) hours = '0' + hours
if (mins < 10) mins = '0' + mins
if (secs < 10) secs = '0' + secs
if (msecs < 10) secs = '0' + msecs
return year+'-'+month+'-'+day + ' ' + hours + ':' + mins + ':' + secs
}
console.log(this.getNowTime())//2022-08-02 11:12:07
// 2.得到今天前后的日期(年月日)
function GetDateStr(AddDayCount) {
var dd = new Date();
dd.setDate(dd.getDate()+AddDayCount);// 获取 AddDayCount 天后的日期
var y = dd.getFullYear();
var m = (dd.getMonth()+1)<10?"0"+(dd.getMonth()+1):(dd.getMonth()+1);// 获取当前月份的日期,不足 10 补 0
var d = dd.getDate()<10?"0"+dd.getDate():dd.getDate();// 获取当前几号,不足 10 补 0
return y+"-"+m+"-"+d;
}
console.log(this.GetDateStr(0))//2022-08-02
console.log(this.GetDateStr(1))//2022-08-03
console.log(this.GetDateStr(-1))//2022-08-01
console.log(this.GetDateStr(-2))//2022-07-31
// 3.date1,date2格式:0000-00-00 00:00:00
// 比较的时间:date1,date2
function compare(date1,date2){
var oDate1 = new Date(date1.replace(/-/g, '/'))
var oDate2 = new Date(date2.replace(/-/g, '/'))
if(new Date(date1)&& new Date(date2)){
if(oDate1.getTime() > oDate2.getTime()){
// alert('date1>date2');
return 1
} else if (oDate1.getTime() < oDate2.getTime()){
// alert('date1<date2');
return 2
}else{
// alert('date1=date2');
return 0
}
}
}
console.log(this.compare('2022-08-02 09:00:00','2022-08-02 10:00:00'))//2
console.log(this.compare('2022-08-02 11:00:00','2022-08-02 10:00:00'))//1
console.log(this.compare('2022-08-02 10:00:00','2022-08-02 10:00:00'))//0
</script>
</html>
前端开发中常用到的时间处理
于 2022-08-02 11:18:12 首次发布