比较两个时间大小
通过调用getTime获取时间戳进行比较
let a = new Date("2022/12/12 00:00:00:000")
let b = new Date("2022/12/20 00:00:00:000")
function compare(a,b){
return a.getTime() > b.getTime()
}
计算两个(年月日)时间的时间差(以天为单位)
let task={
startTime:"2022.12.12",
endTime:"2022.12.20",
}
let startTimeValueAll = parseInt(new Date(task.startTime).getTime()) //转为毫秒值
let endTimeValueAll = parseInt(new Date(task.endTime).getTime()) //转为毫秒值
let actualTime = (endTimeValueAll - startTimeValueAll) / 1000 / 60 / 60 / 24 //计算两个毫秒值的差之后进行转换,转换为天
计算两个时间的时间差(以月为单位)
function monthDiff(startDate, endDate){
return Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth());
}
一步从时间中获取年月日时分秒
let date= new Date()
console.log(date)
function extract(date){
//toISOString会丢失时区,导致时间差八小时,所以在格式化之前需要加上八个小时时间
const d = new Date(new Date(date).getTime() + 8*3600*1000);
return new Date(d).toISOString().split(/[^0-9]/).slice(0, -1);
}
console.log(extract(new Date()))