2019-05-25 17:18:04 +08:00
|
|
|
import * as moment from 'moment';
|
|
|
|
import padStart from 'lodash/padStart';
|
|
|
|
|
|
|
|
import interopDefault from '../_util/interopDefault';
|
|
|
|
|
|
|
|
// Countdown
|
|
|
|
const timeUnits = [
|
|
|
|
['Y', 1000 * 60 * 60 * 24 * 365], // years
|
|
|
|
['M', 1000 * 60 * 60 * 24 * 30], // months
|
|
|
|
['D', 1000 * 60 * 60 * 24], // days
|
|
|
|
['H', 1000 * 60 * 60], // hours
|
|
|
|
['m', 1000 * 60], // minutes
|
|
|
|
['s', 1000], // seconds
|
|
|
|
['S', 1], // million seconds
|
|
|
|
];
|
|
|
|
|
2020-03-07 19:45:13 +08:00
|
|
|
export function formatTimeStr(duration, format) {
|
2019-05-25 17:18:04 +08:00
|
|
|
let leftDuration = duration;
|
|
|
|
|
2020-03-07 19:45:13 +08:00
|
|
|
const escapeRegex = /\[[^\]]*\]/g;
|
|
|
|
const keepList = (format.match(escapeRegex) || []).map(str => str.slice(1, -1));
|
|
|
|
const templateText = format.replace(escapeRegex, '[]');
|
|
|
|
|
|
|
|
const replacedText = timeUnits.reduce((current, [name, unit]) => {
|
2019-05-25 17:18:04 +08:00
|
|
|
if (current.indexOf(name) !== -1) {
|
|
|
|
const value = Math.floor(leftDuration / unit);
|
|
|
|
leftDuration -= value * unit;
|
|
|
|
return current.replace(new RegExp(`${name}+`, 'g'), match => {
|
|
|
|
const len = match.length;
|
|
|
|
return padStart(value.toString(), len, '0');
|
|
|
|
});
|
|
|
|
}
|
|
|
|
return current;
|
2020-03-07 19:45:13 +08:00
|
|
|
}, templateText);
|
|
|
|
|
|
|
|
let index = 0;
|
|
|
|
return replacedText.replace(escapeRegex, () => {
|
|
|
|
const match = keepList[index];
|
|
|
|
index += 1;
|
|
|
|
return match;
|
|
|
|
});
|
2019-05-25 17:18:04 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
export function formatCountdown(value, config) {
|
|
|
|
const { format = '' } = config;
|
|
|
|
const target = interopDefault(moment)(value).valueOf();
|
|
|
|
const current = interopDefault(moment)().valueOf();
|
|
|
|
const diff = Math.max(target - current, 0);
|
|
|
|
return formatTimeStr(diff, format);
|
|
|
|
}
|