vue實(shí)現(xiàn)將時(shí)間戳轉(zhuǎn)換成日期格式
vue將時(shí)間戳轉(zhuǎn)換成日期格式
(1)創(chuàng)建一個(gè)處理時(shí)間格式的js,內(nèi)容如下:
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)在vue文件中需要格式化時(shí)間戳的地方,使用filters過濾器,做如下處理:
<template>
<div class="date">{{item.pass_time | formatDate}}</div>
</template>
<script type="text/ecmascript-6">
import {formatDate} from 'common/js/date'
export default {
filters: {
formatDate(time) {
time = time * 1000
let date = new Date(time)
console.log(new Date(time))
return formatDate(date, 'yyyy-MM-dd hh:mm')
}
}
}
</script>補(bǔ)充:
time應(yīng)為格式為13位unix時(shí)間戳,如果拿到的時(shí)間戳是10位的unix時(shí)間戳,因此需要乘以1000。
vue時(shí)間戳的用法
1.新建一個(gè)js文件用來(lái)存放時(shí)間格式的代碼
代碼如下:
export function timestampToTime(timestamp) {
? ? let now = new Date(timestamp*1000);
? ? let year = now.getFullYear(); ? ?
? ? let month = now.getMonth()+1; ? ?
? ? let date = now.getDate(); ? ?
? ? let hour = now.getHours(); ? ?
? ? let minute = now.getMinutes(); ? ?
? ? let second = now.getSeconds(); ? ?
? ? return year+"-"+month+"-"+date+" ? "+hour+":"+minute+":"+second;
}2.在需要對(duì)時(shí)間戳進(jìn)行格式化處理的組件中引入上面的js文件
代碼如下(示例):
import {timestampToTime} from "@/src/utils/formdate.js"
//對(duì)時(shí)間進(jìn)行格式化
date=timestampToTime(time)總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
基于Vue實(shí)現(xiàn)簡(jiǎn)單的權(quán)限控制
這篇文章主要為大家學(xué)習(xí)介紹了如何基于Vue實(shí)現(xiàn)簡(jiǎn)單的權(quán)限控制,文中的示例代碼講解詳細(xì),具有一定的參考價(jià)值,需要的小伙伴可以了解一下2023-07-07
Vuex(多組件數(shù)據(jù)共享的Vue插件)搭建與使用
Vuex是實(shí)現(xiàn)組件全局狀態(tài)(數(shù)據(jù))管理的一種機(jī)制,可以方便的實(shí)現(xiàn)組件之間數(shù)據(jù)的共享,數(shù)據(jù)緩存等等,下面這篇文章主要給大家介紹了關(guān)于Vuex(多組件數(shù)據(jù)共享的Vue插件)搭建與使用的相關(guān)資料,需要的朋友可以參考下2022-10-10
vue啟動(dòng)報(bào)錯(cuò)‘vue-cli-service serve‘問題及解決
這篇文章主要介紹了vue啟動(dòng)報(bào)錯(cuò)‘vue-cli-service serve‘問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10
一文教會(huì)你搭建vite項(xiàng)目并配置路由和element-plus
由于項(xiàng)目搭建過程實(shí)在繁瑣,容易遺忘,每次新建項(xiàng)目還得百度一下怎么搭建,所以寫下本文提醒自己,下面這篇文章主要給大家介紹了關(guān)于搭建vite項(xiàng)目并配置路由和element-plus的相關(guān)資料,需要的朋友可以參考下2022-07-07
vue實(shí)現(xiàn)四級(jí)導(dǎo)航及驗(yàn)證碼的方法實(shí)例
我們?cè)谧鲰?xiàng)目經(jīng)常會(huì)遇到多級(jí)導(dǎo)航這個(gè)需求,所以下面這篇文章主要給大家介紹了關(guān)于vue實(shí)現(xiàn)四級(jí)導(dǎo)航及驗(yàn)證碼的相關(guān)資料,文章通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2021-07-07

