关于服务器返回时间的前端格式化

问题描述:服务器一般不会返回2020-9-9 11:11这种时间格式,一般都是返回Unix时间元年为起点的相应时间戳,一串数字1535694719,那么前端如何将时间戳转成时间格式字符串呢?

1.将时间戳转成Date对象

//时间戳是秒,Date要求是毫秒,所以*1000
const date = new Date(1535694719*1000)

2.将date进行格式化,转成对应字符串

// 月从0开始
date.getYear() + date.getMonth() + 1

由于这种转换太常见,所以很多语言都有封装

//如java
fmt.format(date,'yyyy-MM-dd')

而js是没有的,下面是一个封装实现

export function dateFormat(fmt, date) {
    
    
    let ret;
    const opt = {
    
    
        "y+": date.getFullYear().toString(),        // 年
        "M+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "h+": date.getHours().toString(),           // 时
        "m+": date.getMinutes().toString(),         // 分
        "s+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加,必须转化成字符串
    };
    for (let k in opt) {
    
    
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
    
    
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
    return fmt;
}

猜你喜欢

转载自blog.csdn.net/qq_39748940/article/details/109306063