vue實現(xiàn)將時間戳轉(zhuǎn)換成日期格式
更新時間:2023年10月10日 14:55:51 作者:yumihe
這篇文章主要介紹了vue實現(xiàn)將時間戳轉(zhuǎn)換成日期格式方式,具有很好的參考價值,希望對大家有所幫助,
vue將時間戳轉(zhuǎn)換成日期格式
(1)創(chuàng)建一個處理時間格式的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文件中需要格式化時間戳的地方,使用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>補充:
time應(yīng)為格式為13位unix時間戳,如果拿到的時間戳是10位的unix時間戳,因此需要乘以1000。
vue時間戳的用法
1.新建一個js文件用來存放時間格式的代碼
代碼如下:
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.在需要對時間戳進行格式化處理的組件中引入上面的js文件
代碼如下(示例):
import {timestampToTime} from "@/src/utils/formdate.js"
//對時間進行格式化
date=timestampToTime(time)總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vuex(多組件數(shù)據(jù)共享的Vue插件)搭建與使用
Vuex是實現(xiàn)組件全局狀態(tài)(數(shù)據(jù))管理的一種機制,可以方便的實現(xiàn)組件之間數(shù)據(jù)的共享,數(shù)據(jù)緩存等等,下面這篇文章主要給大家介紹了關(guān)于Vuex(多組件數(shù)據(jù)共享的Vue插件)搭建與使用的相關(guān)資料,需要的朋友可以參考下2022-10-10
vue啟動報錯‘vue-cli-service serve‘問題及解決
這篇文章主要介紹了vue啟動報錯‘vue-cli-service serve‘問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10
一文教會你搭建vite項目并配置路由和element-plus
由于項目搭建過程實在繁瑣,容易遺忘,每次新建項目還得百度一下怎么搭建,所以寫下本文提醒自己,下面這篇文章主要給大家介紹了關(guān)于搭建vite項目并配置路由和element-plus的相關(guān)資料,需要的朋友可以參考下2022-07-07

