UNPKG

@lakutata/core

Version:

Lakutata Framework Core

84 lines (73 loc) 2.13 kB
import {Plugin} from '../base/Plugin' import momentTimezone from 'moment-timezone' import {Configurable} from '../decorators/DependencyInjection' import sortKeys from 'sort-keys' declare module '../Core' { interface Application { Formatter: Formatter } } export class Formatter extends Plugin { protected get timezone(): string { return <string>process.env.TZ } /** * 默认时间格式 * @type {string} * @protected */ @Configurable() protected readonly dateFormat: string = 'YYYY-MM-DD HH:mm:ss' /** * 格式化为秒时间戳 * @param {string | number | Date} inp * @returns {number} */ public asTimestamp(inp: string | number | Date = new Date()): number { return momentTimezone.tz(inp, this.timezone).unix() } /** * 格式化为毫秒时间戳 * @param {string | number | Date} inp * @returns {number} */ public asMillisecondTimestamp(inp: string | number | Date = new Date()): number { return momentTimezone.tz(inp, this.timezone).valueOf() } /** * 格式化为Date对象 * @param {string | number | Date} inp * @returns {Date} */ public asDate(inp: string | number | Date): Date { return momentTimezone.tz(inp, this.timezone).toDate() } /** * 格式化时间 * @param {Date | string | number} inp * @param {string} format * @returns {string} */ public asDateText(inp: Date | string | number = new Date(), format?: string): string { return momentTimezone.tz(inp, this.timezone).format(format ? format : this.dateFormat) } /** * 百分比格式化 * @param {number} value * @param {number} decimals * @returns {string} */ public asPercent(value: number, decimals: number = 2): string { const val: number = +((value * 100).toFixed(decimals)) return `${val}%` } /** * 对象内容排序(Object或Array均可) * @param {T} obj * @param {{deep?: boolean, compare?: (left: string, right: string) => number}} options * @returns {T} */ public sortObject<T = any>(obj: T, options?: { deep?: boolean; compare?: (left: string, right: string) => number }): T { return sortKeys(obj, options ? options : {deep: true}) } }