vue前端时间格式化,获取当前时间,处理详细解答

1、创建js配置文件写入方法

1、我这里创建的文件名称为system.js

2、以下代码是写好的配置方法,可根据业务需求修改

/*
时间格式化 可获取当前时间  或者传入时间后进行格式化
  * DateFormat
  * format YYYY/yyyy/YY/yy year
  * MM/M month
  * dd/DD/d/D day
  * hh/HH/h/H hour
  * mm/m minute
  * ss/SS/s/S second
  */
export function formatDate(date, formatStr) {

    if (formatStr == null) return null

    var str = formatStr
    var Week = ['日', '一', '二', '三', '四', '五', '六']
    var month = date.getMonth() + 1

    str = str.replace(/yyyy|YYYY/, date.getFullYear())
    str = str.replace(/yy|YY/, (date.getYear() % 100) > 9 ? (date.getYear() % 100).toString() : '0' + (date.getYear() % 100))


    str = str.replace(/MM/, month > 9 ? month : '0' + month)
    str = str.replace(/M/g, month)

    str = str.replace(/w|W/g, Week[date.getDay()])

    str = str.replace(/dd|DD/, date.getDate() > 9 ? date.getDate().toString() : '0' + date.getDate())
    str = str.replace(/d|D/g, date.getDate())

    str = str.replace(/hh|HH/, date.getHours() > 9 ? date.getHours().toString() : '0' + date.getHours())
    str = str.replace(/h|H/g, date.getHours())
    str = str.replace(/mm/, date.getMinutes() > 9 ? date.getMinutes().toString() : '0' + date.getMinutes())
    str = str.replace(/m/g, date.getMinutes())

    str = str.replace(/ss|SS/, date.getSeconds() > 9 ? date.getSeconds().toString() : '0' + date.getSeconds())
    str = str.replace(/s|S/g, date.getSeconds())

    str = str.replace(/t/g, date.getHours() < 12 ? 'am' : 'pm')
    str = str.replace(/T/g, date.getHours() < 12 ? 'AM' : 'PM')

    return str
}
// 获取当前时间 年月日时分分开返回
export function currentTime() {
    function getZero(m) {
        let _m = m
        if (m < 10) {
            _m = '0' + m
        }
        return _m
    }
    let nowDate = new Date();
    return {
        year: nowDate.getFullYear(),
        month: getZero(nowDate.getMonth() + 1),
        day: getZero(nowDate.getDate()),
        hour: nowDate.getHours(),
        minute: getZero(nowDate.getMinutes())
    };
}

2、在页面上使用方法,需引入

import { formatDate, currentTime } from '@/utils/system.js'

3、引入后在页面上直接使用即可,下面代码是完整实例

<template>
    <div>
        <div>{{ currentTime }}</div>
        <div>{{ itme }}</div>
    </div>
</template>

<script>
import { formatDate, currentTime } from '@/utils/system.js'
export default {
    name: "",
    components: {},
    props: {},
    data() {
        return {
            itme: '',
            currentTime: ''
        };
    },
    created() {
        this.currentTime = currentTime() // 对象形式
        this.itme = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss') // 根据配置进行格式化 原逻辑和Element一致
    },
    mounted() { },
    methods: {

    },
};
</script>

<style scoped lang="less"></style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值