• javascript【格式化时间日期】


    javascript【格式化时间日期】 操作:

    (1) 日期格式化代码

    /**
     * 日期格式化函数
    * 调用格式:需要使用日期对象调用 *

    new Date().Format("yyyy/MM/dd HH:mm:ss");

    * @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; }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    (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)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    代码运行结果如下:

    在这里插入图片描述

  • 相关阅读:
    MySQL学习day01
    [Java面试]Spring总结以及在面试中的一些问题.
    C++11相较于C++98 标准新增内容:包装器
    基于SSM的疫苗预约接种平台
    Java关键字,字面量,变量
    Python爬取代理IP
    苏州科技大学计算机考研资料汇总
    C# 监测 Windows 设备变动事件
    计算机网络 | 09.[TCP篇] TCP连接的建立(三次握手)
    甲方与三方渗透团队的协作注意点
  • 原文地址:https://blog.csdn.net/qq_45525848/article/details/132791156