Home > Web Front-end > Vue.js > How to convert timestamp into date in vuejs

How to convert timestamp into date in vuejs

藏色散人
Release: 2023-01-13 00:45:40
Original
4716 people have browsed it

vuejs把时间戳变成日期的方法:1、创建date.js文件并保存到公共js文件夹中;2、在需要格式化时间戳的组件里使用“formatDate(date, 'yyyy-MM-dd hh:mm');”方法进行转换即可。

How to convert timestamp into date in vuejs

本文操作环境:Windows7系统、vue2.9.6版,DELL G3电脑。

vuejs怎么把时间戳变成日期?

vue.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);
};
Copy after login

把上面代码保存为date.js放到你的公共js文件夹中。

在你的需要格式化时间戳的组件里像下面这样使用:

<template>
    <!-- 过滤器  time 可以使后台得到的数据,循环出来的也行 -->
    <div>{{time | formatDate}}</div>
    <!-- 输出结果 -->
    <!-- <div>2016-07-23 21:52</div> -->
</template>
<script>
import {formatDate} from &#39;./common/date.js&#39;;
export default {
    filters: {
        formatDate(time) {
            var date = new Date(time);
            return formatDate(date, &#39;yyyy-MM-dd hh:mm&#39;);
        }
    }
}
</script>
Copy after login

这样就好了

推荐:《最新的5个vue.js视频教程精选

The above is the detailed content of How to convert timestamp into date in vuejs. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template