用replace实现极简时间转换函数

622 阅读1分钟

在日常开发过程中,对时间戳进行格式转换,是经常会遇到的问题,接下来就以replace的方式实现时间转换函数。

编写时间格式化函数:

var formatTime = function (timeStamp, timeType) {
    // 获取时间
    var date = new Date(timeStamp)
    // 获取年月日时分秒
    var yyyy = date.getFullYear();
    var MM = date.getMonth() + 1;
    var dd = date.getDate();
    var hh = date.getHours();
    var mm = date.getMinutes();
    var ss = date.getSeconds();
    // 格式化年月日时分秒
    MM = MM < 10 ? '0' + MM : MM;
    dd = dd < 10 ? '0' + dd : dd;
    hh = hh < 10 ? '0' + hh : hh;
    mm = mm < 10 ? '0' + mm : mm;
    ss = ss < 10 ? '0' + ss : ss;
    // 根据时间格式进行拼接
    return timeType.replace('yyyy', yyyy).replace('MM', MM).replace('dd', dd).replace('hh', hh).replace('mm', mm).replace('ss', ss)
}

调用时间格式化函数:

var date = new Date().getTime();
console.log(formatTime(date, 'yyyy-MM-dd hh:mm:ss'))
console.log(formatTime(date, 'yyyy/MM/dd hh:mm:ss'))
console.log(formatTime(date, 'yyyy年MM月dd日 hh:mm:ss'))
console.log(formatTime(date, 'yyyy-MM-dd'))
console.log(formatTime(date, 'yyyy年MM月'))
console.log(formatTime(date, 'hh:mm:ss'))

输出结果:

// 2023-01-19 14:25:04
// 2023/01/19 14:25:04
// 2023年01月19日 14:25:04
// 2023-01-19
// 2023年01月
// 14:25:04