Files
cashier_wx/utils/countdown.js
2025-12-20 14:41:46 +08:00

51 lines
1.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import dayjs from "dayjs"
/**
* 计算剩余时间差(毫秒)
* @param {Object} item - 包含groupEndTime的订单/拼团对象
* @returns {number} 剩余时间(毫秒)
*/
function returnRemainingTime(item,key) {
if(!item[key]) return 0; // 容错无结束时间则返回0
return dayjs(item[key]).valueOf() - dayjs().valueOf();
}
/**
* 将毫秒差格式化为 HH:MM:SS最多72小时
* @param {number} ms - 时间差(毫秒)
* @returns {string} 格式化后的时分秒(如 09:09:09、72:00:00、00:00:00
*/
function formatTimeToHMS(ms) {
// 边界1已过期/无剩余时间 → 显示00:00:00
if (ms <= 0) return '00:00:00';
// 边界2超过72小时 → 按72小时算72*60*60*1000 = 259200000毫秒
const maxMs = 72 * 60 * 60 * 1000;
const validMs = Math.min(ms, maxMs);
// 转换为总秒数(取整,避免小数)
const totalSeconds = Math.floor(validMs / 1000);
// 拆解小时、分钟、秒
const hours = Math.floor(totalSeconds / 3600);
const remainingSeconds = totalSeconds % 3600;
const minutes = Math.floor(remainingSeconds / 60);
const seconds = remainingSeconds % 60;
// 补零(确保两位数,如 9 → 09
const pad = (num) => String(num).padStart(2, '0');
return `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
}
let timer = null
let nowTime = ref(Date.now())
timer = setInterval(() => {
nowTime.value = Date.now()
}, 1000)
// 组合使用:获取格式化后的剩余时间
export function getRemainingHMS(item,key='groupEndTime') {
const ms = returnRemainingTime(item,key);
return formatTimeToHMS(ms);
}