时间 常用工具函数

dayjs 使用

import * as dayjs from 'dayjs'

dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss') // 1970-00-00 00:00:00
dayjs(dateTime).format('YYYY-MM-DD') // 1970-00-00

// 搜索框使用
dayjs(startTime).startOf('day').format('YYYY-MM-DD HH:mm:ss') // 1970-00-00 00:00:00
dayjs(endTime).endOf('day').format('YYYY-MM-DD HH:mm:ss') // 1970-00-00 23:59:59

IM窗口常用

/**
 * @description 时间格式化方法
 *
 * @param {(Object|string|number)} time
 * @param {String} cFormat
 * @returns {String | null}
 */
export function parseTime(time, cFormat) {
    if (arguments.length === 0) {
        return null
    }

    let date
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'

    if (typeof time === 'object') {
        date = time
    } else {
        if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
            time = parseInt(time)
        }
        if (typeof time === 'number' && time.toString().length === 10) {
            time = time * 1000
        }
        date = new Date(time)// new Date(time.replace(/-/g, '/'))
    }

    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }

    const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') {
            return ['日', '一', '二', '三', '四', '五', '六'][value]
        }

        return value.toString().padStart(2, '0')
    })

    return time_str
}

/**
 * @description 人性化时间显示
 *
 * @param {number} datetime 13位时间戳
 */
export function formateTime(datetime) {
    if (datetime == null) return ''

    const time = new Date()
    const outTime = new Date(datetime)

    if (
        time.getTime() < outTime.getTime() ||
        time.getFullYear() != outTime.getFullYear()
    ) {
        return parseTime(outTime, '{y}-{m}-{d} {h}:{i}')
    }

    if (time.getMonth() !== outTime.getMonth()) {
        return parseTime(outTime, '{m}-{d} {h}:{i}')
    }

    if (time.getDate() !== outTime.getDate()) {
        const day = outTime.getDate() - time.getDate()
        if (day === -1) {
            return parseTime(outTime, '昨天 {h}:{i}')
        }

        if (day === -2) {
            return parseTime(outTime, '前天 {h}:{i}')
        }

        return parseTime(outTime, '{m}-{d} {h}:{i}')
    }

    if (time.getHours() !== outTime.getHours()) {
        return parseTime(outTime, '{h}:{i}')
    }

    let minutes = outTime.getMinutes() - time.getMinutes()
    if (minutes === 0) {
        return '刚刚'
    }

    minutes = Math.abs(minutes)
    return `${minutes}分钟前`
}
posted @ 2022-08-03 16:05  卑面派对  阅读(49)  评论(0编辑  收藏  举报