vue 关于日期、时间戳格式的一些操作

/**
 * 时间戳转换为日期格式 YYYY-MM-DD HH:MM:SS
 * nowss:时间戳,若时间戳为13位时则不需要乘以1000,10位才需要
 * 需要转换成字符串才能获取数字长度
 */
export const formatDate = (nowss) => {
    let times = String(nowss).length === 10 ? new Date(nowss * 1000) : new Date(nowss)
    var year = times.getFullYear() //取得4位数的年份
    var month = times.getMonth() + 1 //取得日期中的月份,其中0表示1月,11表示12月
    var day = times.getDate() //返回日期月份中的天数(1到31)
    var hour = times.getHours() //返回日期中的小时数(0到23)
    var minute = times.getMinutes() //返回日期中的分钟数(0到59)
    var second = times.getSeconds() //返回日期中的秒数(0到59)
    return [year, month, day].map(formatNumber).join("-") + " " + [hour, minute, second].map(formatNumber).join(":")
}

// 日期格式YYYY-MM-DD HH:MM:SS
export const formatTime = (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(":")
}

// 时间格式 HH:MM:SS
export const formatAtTimes = (date) => {
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    return [hour, minute, second].map(formatNumber).join(":")
}

const formatNumber = (n) => {
    n = n.toString()
    return n[1] ? n : "0" + n
}

// 日期格式YYYY-MM-DD HH:MM:SS 截取值YYYY-MM-DD
export const splitDate = (date) => {
    return date.split(" ")[0]
}

猜你喜欢

转载自blog.csdn.net/u014678583/article/details/129100064