这段代码是我常用来格式化日期用的,很好用。

Date.prototype.toLocaleString = function () {   // 重写日期函数格式化日期
       return `${this.getFullYear()}-${this.getMonth() + 1 >= 10 ? (this.getMonth() + 1) : '0' + (this.getMonth() + 1)}-${this.getDate() >= 10 ? this.getDate() : '0' + this.getDate()}
                 ${this.getHours() >= 10 ? this.getHours() : '0' + this.getHours()} : ${this.getMinutes()>=10?this.getMinutes():'0'+this.getMinutes()} : ${this.getSeconds() >= 10 ? this.getSeconds() : '0' + this.getSeconds()}`;
            };

使用办法

格式化后的日期 = new Date(这里是传入的毫秒值).toLocaleString();

Vue实例

写到这里大家一定都懂了,不懂的话,我写了一个Vue实例看看:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>使用Vue格式化日期---原创马优晨</title>
    <script src="https://cdn.bootcss.com/vue/2.5.17-beta.0/vue.js"></script>
</head>
<script>
window.onload = function(){
    var app = new Vue({
        el: '#app',
        data:{
            timeMes:""
        },
        created() {
            let self = this;
            self.timeMes = self.dataFormat(new Date(1522611151000))
            new Date(element.followTime)
        },
        methods:{
            dataFormat(time){
                return `${time.getFullYear()}-${time.getMonth() + 1 >= 10 ? (time.getMonth() + 1) : '0' + (time.getMonth() + 1)}-${time.getDate() >= 10 ? time.getDate() : '0' + time.getDate()}
                     ${time.getHours() >= 10 ? time.getHours() : '0' + time.getHours()} : ${time.getMinutes()>=10?time.getMinutes():'0'+time.getMinutes()} : ${time.getSeconds() >= 10 ? time.getSeconds() : '0' + time.getSeconds()}`;
             }
        }
    })
}

</script>
<body>
    <div id="app">
        作者:马优晨    时间:{{timeMes}}
    </div>
</body>
</html>

效果图:

这里写图片描述

如果下图的“通话时长”的这种时间:
在这里插入图片描述

处理函数:

    timeDeal(time) {   // time 是一个时间戳
      const timer = +time;
      const minutes = Math.floor(timer / 60);
      const seconds =
        (timer % 3600) % 60 > 9
          ? (timer % 3600) % 60
          : `0${(timer % 3600) % 60}`;

      return `${minutes}'${seconds}''`;
    }
Logo

前往低代码交流专区

更多推荐