UNPKG

vtils

Version:

一个面向业务的 JavaScript/TypeScript 实用程序库。

52 lines (49 loc) 1.46 kB
import { lightFormat } from 'date-fns'; /** * 日期格式化占位符。 * * @public */ export var FormatDatePlaceholder = /*#__PURE__*/function (FormatDatePlaceholder) { FormatDatePlaceholder["y"] = "y"; FormatDatePlaceholder["yyyy"] = "yyyy"; FormatDatePlaceholder["m"] = "M"; FormatDatePlaceholder["mm"] = "MM"; FormatDatePlaceholder["d"] = "d"; FormatDatePlaceholder["dd"] = "dd"; FormatDatePlaceholder["h"] = "H"; FormatDatePlaceholder["hh"] = "HH"; FormatDatePlaceholder["i"] = "m"; FormatDatePlaceholder["ii"] = "mm"; FormatDatePlaceholder["s"] = "s"; FormatDatePlaceholder["ss"] = "ss"; return FormatDatePlaceholder; }({}); /** * 日期格式化渲染器。 * * @public * @param placeholders 占位符 * @returns 返回渲染字符串 */ /** * 格式化日期。 * * @public * @param date 要格式化的日期,支持 Date、秒或毫秒时间戳 * @param renderer 渲染器 * @returns 返回格式化后的日期 * @example * ```typescript * formatDate( * new Date(2020, 5 - 1, 20, 13, 14, 21), * _ => `${_.yyyy}-${_.mm}-${_.dd} ${_.hh}:${_.ii}:${_.ss}`, * ) // => '2020-05-20 13:14:21' * ``` */ export function formatDate(date, renderer) { if (typeof date === 'number' && String(date).length === 10) { date *= 1000; } return lightFormat(date, typeof renderer === 'string' ? renderer.replace(/m/g, 'M').replace(/h/g, 'H').replace(/i/g, 'm') : renderer(FormatDatePlaceholder)); }