UNPKG

t-comm

Version:

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

89 lines (87 loc) 2.61 kB
/** * 将时间戳格式化 * @param {number} timestamp * @param {string} fmt * @param {string} [defaultVal] * @returns {string} 格式化后的日期字符串 * @example * * const stamp = new Date('2020-11-27 8:23:24').getTime(); * * const res = timeStampFormat(stamp, 'yyyy-MM-dd hh:mm:ss') * * // 2020-11-27 08:23:24 */ function timeStampFormat(timestamp, fmt, defaultVal, whitePrefix) { if (whitePrefix === void 0) { whitePrefix = ''; } if (!timestamp) { return defaultVal || ''; } var date = new Date(); if ("".concat(timestamp).length === 10) { timestamp *= 1000; } date.setTime(timestamp); var o = { 'M+': date.getMonth() + 1, 'd+': date.getDate(), 'h+': date.getHours(), 'm+': date.getMinutes(), 's+': date.getSeconds(), 'q+': Math.floor((date.getMonth() + 3) / 3), S: date.getMilliseconds() // 毫秒 }; var reg = /(y+)/; if (whitePrefix) { reg = new RegExp("(?:^|(?:[^".concat(whitePrefix, "y]))(y+)")); } var match = fmt.match(reg); if (match === null || match === void 0 ? void 0 : match[1]) { fmt = fmt.replace(match[1], "".concat(date.getFullYear()).slice(4 - match[1].length)); } // eslint-disable-next-line no-restricted-syntax for (var k in o) { var reg_1 = new RegExp("(".concat(k, ")")); if (whitePrefix) { reg_1 = new RegExp("(?:^|(?:[^".concat(whitePrefix).concat(k[0], "]))(").concat(k, ")")); } match = fmt.match(reg_1); if (match === null || match === void 0 ? void 0 : match[1]) { var _a = match.index, index = _a === void 0 ? 0 : _a; var realIndex = whitePrefix ? index + match[0].length - match[1].length : index; var str = "".concat(o[k]); var len = match[1].length; var replacePart = len === 1 ? str : "00".concat(str).slice("".concat(str).length); fmt = fmt.slice(0, realIndex) + replacePart + fmt.slice(realIndex + len); // fmt = fmt.replace( // match[1], // match[1].length === 1 ? str : `00${str}`.slice(`${str}`.length), // ); } } if (whitePrefix) { fmt = fmt.replace(new RegExp(whitePrefix, 'g'), ''); } return fmt; } /** * 将日期格式化 * @param {Date} date * @param {string} format * @returns {string} 格式化后的日期字符串 * @example * * const date = new Date('2020-11-27 8:23:24'); * * const res = dateFormat(date, 'yyyy-MM-dd hh:mm:ss') * * // 2020-11-27 08:23:24 */ function dateFormat(date, fmt) { var timestamp = new Date(date).getTime(); return timeStampFormat(timestamp, fmt); } export { dateFormat, timeStampFormat };