信息发布→ 登录 注册 退出

vue中对时间戳的处理方式

发布时间:2026-01-11

点击量:
目录
  • vue对时间戳的处理
    • 1、自建js文件
    • 2、在组件模板中引用定义好的时间戳函数
    • 3、设置好在script中的引用和定义
  • vue时间戳转换

    vue对时间戳的处理

    1、自建js文件

    文件位置根据自己的项目位置自定义

    export function formatDate(date, fmt) {
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        let o = {
            'M+': date.getMonth() + 1,
            'd+': date.getDate(),
            'h+': date.getHours(),
            'm+': date.getMinutes(),
            's+': date.getSeconds()
        };
        for (let k in o) {
            if (new RegExp(`(${k})`).test(fmt)) {
                let str = o[k] + '';
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
            }
        }
        return fmt;
    };
    function padLeftZero(str) {
        return ('00' + str).substr(str.length);
    };

    2、在组件模板中引用定义好的时间戳函数

    <template>
        <div>{{time | formatDate}}</div>
    </template>

    3、设置好在script中的引用和定义

    <script>
    import {formatDate} from 'xxx.js';
    export default {
        filters: {
            formatDate(time) {
                var date = new Date(time);
                return formatDate(date, 'yyyy-MM-dd hh:mm');
            }
        }
    }
    </script>

    vue时间戳转换

    后台拿时间数据,一般不是时间格式,而是一串数组,这个时候就需要转换,然后才可以使用了

     add_time(row, column, cellValue, index) {
            if (cellValue == null || cellValue == "") return "";
            let date = new Date(parseInt(cellValue) * 1000);
            let Y = date.getFullYear() + '-';
            let M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) + '-' : date.getMonth() + 1 + '-';
            let D = date.getDate() < 10 ? '0' + date.getDate() + ' ' : date.getDate() + ' ';
            let h = date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':';
            let m = date.getMinutes() < 10 ? '0' + date.getMinutes() + ':' : date.getMinutes() + ':';
            let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
            return Y + M + D;
          },

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持。 

    在线客服
    服务热线

    服务热线

    4008888355

    微信咨询
    二维码
    返回顶部
    ×二维码

    截屏,微信识别二维码

    打开微信

    微信号已复制,请打开微信添加咨询详情!