Skip to content

Instantly share code, notes, and snippets.

@giscafer
Created January 24, 2019 02:13
Show Gist options
  • Save giscafer/87c2bc7bf358fd3cee1e57a518265ba7 to your computer and use it in GitHub Desktop.
Save giscafer/87c2bc7bf358fd3cee1e57a518265ba7 to your computer and use it in GitHub Desktop.
48小时订单倒计时
const orderCancelTime = 48 * 3600 * 1000;
const timeCountDown = orderCancelTime - (30 * 60 * 1000); // 半小时开始倒计时
const farawayTime = orderCancelTime - (60 * 60 * 1000); // 1小时以上不倒计时,避免定时器性能问题
export const formatByTimestamp = (timestamp, hasHour) => {
let second = Math.floor(timestamp / 1000);
if (second < 1) {
return '';
}
let totalMinutes = Math.floor(second / 60);
let _second = second % 60;
let _secondText = '';
_secondText = _second >= 10 ? _second : `0${_second}`;
if (!hasHour) {
if (totalMinutes === 0) {
return _secondText;
}
let minuteText = totalMinutes >= 10 ? totalMinutes : `0${totalMinutes}`;
return `${minuteText}:${_secondText}`;
}
let hours = Math.floor(totalMinutes / 60);
let minutes = Math.floor(totalMinutes % 60);
const hoursText = hours >= 10 ? hours : `0${hours}`;
const minutesText = minutes >= 10 ? minutes : `0${minutes}`;
if (hours === 0) {
return `${minutesText}:${_secondText}`;
}
return `${hoursText}:${minutesText}:${_secondText}`;
}
/**
* 判断是否有必要计时
* @param {*} submitTime
*/
export const isTimeToCount = (submitTime) => {
try {
submitTime = submitTime.replace(/-/g, '/');
let time = new Date(submitTime).getTime();
let now = new Date().getTime();
if ((time + farawayTime) - now > 0) {
return false;
}
return true;
} catch (e) {
return false;
}
}
/**
* 实时获取当前时间字符串
* @param {*} date
*/
// 订单48小时超时(ms),最后半小时才倒计时
export const submitTimeCountDown = submitTime => {
if (!submitTime) return '';
try {
submitTime = submitTime.replace(/-/g, '/');
let time = new Date(submitTime).getTime();
let now = new Date().getTime();
if ((time + timeCountDown) - now > 0) {
return '';
}
let count = (time + orderCancelTime) - now;
// console.log(count)
return formatByTimestamp(count);
} catch (e) {
}
}
// 订单48小时超时(ms),一开始就倒计时
export const submitTimeCountDownAll = submitTime => {
if (!submitTime) return '';
try {
submitTime = submitTime.replace(/-/g, '/');
let time = new Date(submitTime).getTime();
let now = new Date().getTime();
if ((time + orderCancelTime) - now < 0) {
// 已经超过48小时
return '';
}
let count = (time + orderCancelTime) - now;
// console.log(count)
return formatByTimestamp(count, true);
} catch (e) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment