zl程序教程

您现在的位置是:首页 >  前端

当前栏目

javascript常用代码【格式化时间日期】

JavaScript日期代码 时间 常用 格式化
2023-09-14 09:13:55 时间

这周工作中,写了几个前端界面,页面中有个表格列字段是时间类型的,但是后端传递过来的时间是时间戳,所以需要在前端将其转换展示。

记录一下格式化日期代码,以后再遇见类似功能直接复制黏贴即可(其实是为了多点时间摸鱼):

(1) 日期格式化代码

/**
 * 日期格式化函数<br/>
 * 调用格式:需要使用日期对象调用
 * <p> new Date().Format("yyyy/MM/dd HH:mm:ss"); </p>
 * @param fmt 日期格式
 * @returns {*} 返回格式化后的日期
 * @constructor
 */
Date.prototype.Format = function (fmt) {
    var object = {
        "M+": this.getMonth() + 1, // 月
        "d+": this.getDate(), // 日
        "H+": this.getHours(), // 时
        "m+": this.getMinutes(), // 分
        "s+": this.getSeconds(), // 秒
        "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
        "S": this.getMilliseconds() // 毫秒
    };
    // 正则表达式
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var pattern in object) {
        if (new RegExp("(" + pattern + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (object[pattern]) : (("00" + object[pattern]).substr(("" + object[pattern]).length)));
        }
    }
    return fmt;
}

(2) 函数调用

使用一个Date对象去调用Format函数即可。

时间戳转换,如果是时间戳需要转换,则需要注意的是,时间戳是10位长度的,还是13位长度的,如果是10位长度的时间戳,那么就需要乘以1000后,在调用Format进行转换

举例如下:

// 调用函数
// 年月日
var date1 = new Date().Format("yyyy/MM/dd")
console.log(date1)
// 年月日 时分秒 毫秒
var date2 = new Date().Format("yyyy/MM/dd HH:mm:ss.S")
console.log(date2)
// 年月日 时分秒 毫秒 季度
var date3 = new Date().Format("yyyy/MM/dd HH:mm:ss.S qq")
console.log(date3)
// 时间戳
var date4 = new Date(1609430400000).Format("yyyy/MM/dd HH:mm:ss.S qq")
console.log(date4)

代码运行结果如下: