時間戳轉成時間格式化字符串(常用)


//formatData.js //封裝的formatDate函數 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); };


//vue組件
<template> <div class="comment-info-wrap"> <!-- commentInfo.created是傳進來的時間戳65132165464,單位為秒 --> <span class="comment-time">
<!-- 使用showDate方法對時間戳進行過濾格式化--> {{ commentInfo.created | showDate }} </span> </div> </template> <script> import { formatDate } from "common/formatDate"; export default { name: "DetailCommentInfo", props: { commentInfo: { type: Object, default() { return {}; } } }, filters: { showDate(value) { //將時間戳轉換成date對象 const date = new Date(value * 1000);//這里需要將時間戳乘以1000,轉為毫秒,具體看請求過來的數據 //將date進行格式化 return formatDate(date, "yyyy-MM-dd hh:mm:ss"); } } }; </script>

 

步驟總結:

1.將時間戳轉為Data對象,const date =new Date(1535694719*1000)

2.將date進行格式化,使用封裝的formatDate函數即可

3.注意字母大小寫:"yyyy-MM-dd hh:mm:ss"

4.hh為12小時,HH為24小時


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM