UNPKG

t-comm

Version:

专业、稳定、纯粹的工具库

78 lines (74 loc) 2.13 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); /** * 将毫秒数time转化为倒计时 * @param time 倒计时时间,毫秒单位 * @param format 倒计时格式化字符串,例如:dd天hh小时mm分ss秒SSS毫秒,hh:mm:ss.SSS,hh:mm:ss * @example * ```ts * transformTime(1000, 'hh:mm:ss') * ``` */ function transformTime(time, format) { var days = Math.floor(time / 86400000); // 日 var hours = Math.floor(time % 86400000 / 3600000); // 小时 var minutes = Math.floor(time % 3600000 / 60000); // 分 var seconds = Math.floor(time % 60000 / 1000); // 秒 var milliseconds = Math.floor(time % 1000); // 毫秒 var obj = { 'd+': days, 'D+': days, 'h+': hours, 'H+': hours, 'm+': minutes, 'M+': minutes, 's+': seconds, 'S+': milliseconds }; var timeData = { days: days, hours: hours, minutes: minutes, seconds: seconds, milliseconds: milliseconds }; var timeList = []; var timeText = format; var _loop_1 = function _loop_1(prop) { var regex = new RegExp("(".concat(prop, ")")); var matchResult = regex.exec(timeText); if (matchResult) { timeText = timeText.replace(matchResult[1], function (match, offset, source) { var numStr = "".concat(obj[prop]); var digit = numStr; if (match.length > 1) { digit = (match.replace(new RegExp(match[0], 'g'), '0') + numStr).substring(numStr.length); } var unit = source.substr(offset + match.length); var last = timeList[timeList.length - 1]; if (last) { var index = last.unit.indexOf(match); if (index !== -1) { last.unit = last.unit.substring(0, index); } } timeList.push({ digit: digit, unit: unit, match: match }); return digit; }); } }; // eslint-disable-next-line no-restricted-syntax for (var prop in obj) { _loop_1(prop); } return { timeText: timeText, timeList: timeList, timeData: timeData }; } exports.transformTime = transformTime;