JavaScript 时间转时间

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

JavaScript 时间转时间

liyinchi1988   2022-09-29 我要评论

1、date.getTime()

2、date.valueOf()

3、Date.parse(date)

第一、第二种:会精确到毫秒

第三种:只能精确到秒,毫秒用000替代

注意:获取到的时间戳除以1000就可获得Unix时间戳,就可传值给后台得到。

4.时间戳转年月日时分秒

// 时间戳转年月日
getYMDHMS(timestamp) {
			var date = new Date(); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
			var Y = date.getFullYear() + '-';
			var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
			var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
			var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
			var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
			var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
 
				var strDate = Y + M + D + h + m + s;
				return strDate;
},

5.当前时间往前推30天、7天、3天

this.getData(-30);//前推30天
this.getData(-7);//前推7天
this.getData(-3);//前推3天
 
 
getData(day){
    var today=new Date()
    var targetday=today.getTime() +1000*60*60*24* day
    today.setTime(targetday)
    var tYear=today.getFullYear()
    var tMonth=today.getMonth()
    var tDate=today.getDate()
    tMonth=this.doHandMonth(tMonth+1)
    tDate=this.doHandMonth(tDate)
    return tYear +"-" + tMonth+"-"+tDate
}
 
 
doHandMonth(month){
    var m=month
    if(month.toString().length==1){
    m="0"+month
    }
    return m
}

6.获取最近七天日期

//返回最近七天的日期
	getday2() {
		let days = [];
		for(let i=0; i<=24*6;i+=24){		//今天加上前6天
			let dateItem=new Date(Date.getTime() - i * 60 * 60 * 1000);	//使用当天时间戳减去以前的时间毫秒(小时*分*秒*毫秒)
			let y = dateItem.getFullYear();	//获取年份
			let m = dateItem.getMonth() + 1;	//获取月份js月份从0开始,需要+1
			let d= dateItem.getDate();	//获取日期
			m = this.addDate0(m);	//给为单数的月份补零
			d = this.addDate0(d);	//给为单数的日期补零
			let valueItem= y + '-' + m + '-' + d;	//组合
			days.push(valueItem);	//添加至数组
		}
		console.log('最近七天日期:',days);
 
		return days;
	},

	//给日期加0
	addDate0(time) {
		if (time.toString().length == 1) {
			time = '0' + time.toString();
		}
		return time;
	},

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们