uniapp开发小程序—— 获取当前时间、比较两个时间/日期的大小

1.获取当前时间的方法:

//获取当前时间
getNewTime() {
    
    
	//new Date().getTime() 可以直接获取当前的时间戳
	this.nowTime = this.traversalTime(new Date().getTime())   //在data里定义变量-nowTime
	console.log('当前时间', this.nowTime) //2023-04-13 17:23:24
	// console.log(new Date(this.nowTime))
},
addTimes(m) {
    
    
	return m < 10 ? '0' + m : m
},
traversalTime(timestamp) {
    
    
	//timestamp(时间戳)是整数,否则要parseInt转换
	let time = new Date(timestamp);
	let y = time.getFullYear();
	let m = time.getMonth() + 1;
	let d = time.getDate();
	let h = time.getHours();
	let mm = time.getMinutes();
	let s = time.getSeconds();
	return y + '-' + this.addTimes(m) + '-' + this.addTimes(d) + ' ' + this.addTimes(h) + ':' + this.addTimes(mm) + ':' + this.addTimes(s);

	/***********判断当前时间是上午还是下午************/
	 if (h>= 0 && h < 12) {
    
    
         this.hoursTip = "上午"
     } else if (h >= 12 && h < 18) {
    
    
         this.hoursTip = "下午"
     } else {
    
    
         this.hoursTip = "晚上"
     }
},

2.比较两个时间/日期的大小(我这里是判断报名时间有无截止)

that.enrollEndTime = res.data.data.end_time; //报名截止时间(接口返回的)
//比较两个时间/日期的大小
let obj1 = new Date(that.nowTime) //当前时间
let obj2 = new Date(that.enrollEndTime) //报名截止时间
// console.log('打印一下-当前时间',obj1)
// console.log('打印一下-报名截止时间',obj2)
if (obj1.getTime() > obj2.getTime()) {
    
    
	console.log('报名已截止')
	that.enrollIsEnd = true
} else {
    
    
	console.log('报名没有截止')
	that.enrollIsEnd = false
}

完成!~

猜你喜欢

转载自blog.csdn.net/weixin_48596030/article/details/130153516