前端js时间戳互转年月日时分秒,前端js两个年月日时分秒时间相减获得时间差,相差几天几月几日几时几分几秒,直接复制即用。

// 传时间戳转年月日时分秒

msToDate(milliseconds) {
	var date = new Date(milliseconds)
	var year = date.getFullYear();
	var month = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
	var day = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
	var hours = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours());
	var minutes = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes());
	var seconds = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds())
	var dateTime = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds
	console.log(dateTime)
	return dateTime;
}


// 传时间转时间戳

msToDate(milliseconds) {
    var date = new Date(milliseconds)
	var dateTime = date.getTime()
	console.log(dateTime)
	return dateTime;
}

// 两年月日时分秒相减获得时间差

// 当前时间
const myDate = new Date(); 
// 另一时间
let dat = this.option.passTime
let  getYeardata = dat.split(" ")[0];
let  getTimedata = dat.split(" ")[1];
//  年月日  时分秒
const beforeYear = getYeardata.split("-")[0];
const beforeMonth = getYeardata.split("-")[1];
const beforeDate = getYeardata.split("-")[2];
const beforeHours = getTimedata.split(":")[0];
const beforeMinutes = getTimedata.split(":")[1];
const beforeSeconds = getTimedata.split(":")[2];
// 相差年
czyear = Math.abs(myDate.getFullYear() - beforeYear)
// 相差月
czmonth = Math.abs(myDate.getMonth() - beforeMonth +1)
// 相差日
czdate = Math.abs(myDate.getDate() - beforeDate)
// 相差时
czhours = Math.abs(myDate.getHours() -  beforeHours)
// 相差分
czminutes = Math.abs(myDate.getMinutes() - beforeMinutes)
// 相差秒
czseconds = Math.abs(myDate.getSeconds() - beforeSeconds)


// 两时间相减获得时间差

getHoursDifference(time1, time2) {
	var now = new Date();
	// 设置时间1
	now.setHours(time1.split(':')[0], time1.split(':')[1]);
	// 设置时间2
	var endTime = new Date();
	endTime.setHours(time2.split(':')[0], time2.split(':')[1]);
	// 计算时间差(毫秒)
	var diff = endTime.getTime() - now.getTime();
	// 将时间差转换成小时和分钟
	var hours = Math.floor(diff / 3600000);
	var minutes = Math.floor((diff % 3600000) / 60000);
	console.log(hours,'hours')
	console.log(minutes,'minutes')
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值