1.格式化时间
<p>{{formattedTime('1712054698000')}}</p>
const formattedTime = (time: any) => {
const date = new Date(time)
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
const hours = String(date.getHours()).padStart(2, '0')
const minutes = String(date.getMinutes()).padStart(2, '0')
const seconds = String(date.getSeconds()).padStart(2, '0')
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
2.获取开始时间和结束时间中间的时长
<p>{{setTime('1712052379000','1712053006000')}}</p>
const getTime = (startTime: any, endTime: any) => {
const start: any = new Date(startTime)
const end: any = new Date(endTime)
let diff: any = end - start
//年
const years = Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25)).toString().padStart(2, '0');
diff %= 1000 * 60 * 60 * 24 * 365.25;
//月
const months = Math.floor(diff / (1000 * 60 * 60 * 24 * 30)).toString().padStart(2, '0');
diff %= 1000 * 60 * 60 * 24 * 30;
//日
const days = Math.floor(diff / (1000 * 60 * 60 * 24)).toString().padStart(2, '0');
diff %= 1000 * 60 * 60 * 24;
//时
const hours: any = Math.floor(diff / (1000 * 60 * 60)).toString().padStart(2, '0')
diff %= 1000 * 60 * 60
//分
const minutes: any = Math.floor(diff / (1000 * 60)).toString().padStart(2, '0')
diff %= 1000 * 60
//秒
const seconds: any = Math.floor(diff / 1000).toString().padStart(2, '0')
return `${years}:${months}:${days} ${hours}:${minutes}:${seconds}`
}
//.toString().padStart(2, '0')转换为字符串补零
3.获取n小时以后的时间
//value是要加多少个小时
const addHours = (value:any) => {
const time: any = value
const newDate = new Date(time.replace(/-/g, '/'))
newDate.setHours(newDate.getHours() + n)
return newDate
}