// 传时间戳转年月日时分秒
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')
}
前端js时间戳互转年月日时分秒,前端js两个年月日时分秒时间相减获得时间差,相差几天几月几日几时几分几秒,直接复制即用。
于 2024-05-06 10:09:10 首次发布