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應為格式為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)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue3.0使用mapState,mapGetters和mapActions的方式
這篇文章主要介紹了vue3.0使用mapState,mapGetters和mapActions的方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06

