import moment from 'moment' export const formatTime = (date: Date) => { const year = date.getFullYear() const month = date.getMonth() + 1 const day = date.getDate() const hour = date.getHours() const minute = date.getMinutes() const second = date.getSeconds() return ( [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':') ) } /// 格式化日期 export function formatDate(date: Date) { date = new Date(date); return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`; } /** * 日期格式化 * @param value * @param format * @returns */ export function formatDateString(value?: string, format = 'YYYY-MM-DD HH:mm:ss') { if (value) { return moment(value).format(format) } return handleNoneValue() } /** * 处理空值的情况 * @param value 值 * @param suffix 后缀名 * @returns */ export function handleNoneValue(value?: T, suffix = '') { if (value == null || String(value) === '') { return '--' } return value + suffix } const formatNumber = (n: number) => { const s = n.toString() return s[1] ? s : '0' + s } /// 判断字符串是否为空 export const isnullstr = (str: string) => { return str == '' ? '--' : str } /// 截取两位小数位 export const getDecimalNum = (number: string) => { let amount = number let num = null // 小数点后最多只能输入两位 num = number.replace(new RegExp('^(\\d+\\.\\d{2}).+'), '$1') // 小数点开头得话,让前面加个0 eg: 0.xx const startPoint = /^\./g if (startPoint.test(num)) { num = amount.replace(startPoint, '0.') } // 若没有小数点,前面输入多个0,去掉0取整 // if(num有值 && 没有小数点 && 不等于'0') if (num && !num.includes('.') && num !== '0') { num = +num } // 若出现多个小数点,则替换为1个 const morePoint = /\.+(\d*|\.+)\./g if (morePoint.test(String(num))) { num = amount .replace(/\.{2,}/g, ".") .replace(".", "$#$") .replace(/\./g, "") .replace("$#$", ".") } return num }