• 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

    代码运行结果如下:

    在这里插入图片描述

  • 相关阅读:
    ROS2--概述
    CSS特效002:花样的鼠标悬停效果
    SQL设计时增加说明列
    主机jvisualvm连接到tomcat服务器查看jvm状态
    网站架构演变、LNP+Mariadb数据库分离、Web服务器集群、Keepalived高可用
    关于#Shape#的问题,如何解决?
    《痞子衡嵌入式半月刊》 第 75 期
    JAVA学习第九课:用Swing开发GUI程序
    首发 自媒体博客最新版Spimes主题 X6.0开心免授权
    [MySQL]-压力测试之Sysbench
  • 原文地址:https://blog.csdn.net/qq_45525848/article/details/132791156