前端常見的時(shí)間轉(zhuǎn)換方法以及獲取當(dāng)前時(shí)間方法小結(jié)
更新時(shí)間:2024年01月22日 15:22:17 作者:起名時(shí)在學(xué)Aiifox
在做開發(fā)時(shí)會對不同的時(shí)間格式進(jìn)行轉(zhuǎn)換,下面這篇文章主要給大家介紹了關(guān)于前端常見的時(shí)間轉(zhuǎn)換方法以及獲取當(dāng)前時(shí)間方法的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
1、獲取當(dāng)前年月日時(shí)間
getCurrentDate() { const date = new Date(); const year = date.getFullYear(); const month = date.getMonth() + 1; // JavaScript的月份是從0開始的,所以需要加1 const day = date.getDate(); const hours = date.getHours().toString().padStart(2, '0'); // 補(bǔ)零 const minutes = date.getMinutes().toString().padStart(2, '0'); // 補(bǔ)零 this.currentDate = `${year}-${month}.${day}-${hours}:${minutes}`; },
2、將時(shí)間戳轉(zhuǎn)換為指定格式
function formatTime(time, format) { const date = new Date(time); const year = date.getFullYear(); const month = (date.getMonth() + 1).toString().padStart(2, '0'); const day = date.getDate().toString().padStart(2, '0'); const hour = date.getHours().toString().padStart(2, '0'); const minute = date.getMinutes().toString().padStart(2, '0'); const second = date.getSeconds().toString().padStart(2, '0'); let result = ''; switch (format) { case 'yyyy-MM-dd': result = `${year}-${month}-${day}`; break; case 'yyyy/MM/dd': result = `${year}/${month}/${day}`; break; case 'yyyy年MM月dd日': result = `${year}年${month}月${day}日`; break; case 'HH:mm:ss': result = `${hour}:${minute}:${second}`; break; default: result = `${year}-${month}-${day} ${hour}:${minute}:${second}`; } return result; }
3、vue中時(shí)間轉(zhuǎn)換插件:moment.js
官網(wǎng):Moment.js 中文網(wǎng)
(1)下載安裝包
npm install moment --save
(2)在main.js中引入
import moment from 'moment' Vue.prototype.$moment = moment
(3)使用
this.$moment('需要轉(zhuǎn)換的時(shí)間').format('YYYY-MM-DD')
總結(jié)
到此這篇關(guān)于前端常見的時(shí)間轉(zhuǎn)換方法以及獲取當(dāng)前時(shí)間方法的文章就介紹到這了,更多相關(guān)前端時(shí)間轉(zhuǎn)換及獲取當(dāng)前時(shí)間內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
微信小程序bindtap與catchtap的區(qū)別詳解
本文主要介紹了微信小程序bindtap與catchtap的區(qū)別詳解,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09根據(jù)輸入郵箱號跳轉(zhuǎn)到相應(yīng)登錄地址的解決方法
本文分享了基于javascript實(shí)現(xiàn)的根據(jù)輸入郵箱號跳轉(zhuǎn)到相應(yīng)登錄地址的具體實(shí)例代碼,需要的朋友一起來看下吧2016-12-12根據(jù)地區(qū)不同顯示時(shí)間的javascript代碼
根據(jù)地區(qū)不同顯示時(shí)間的javascript代碼...2007-08-08JS基于對象的特性實(shí)現(xiàn)去除數(shù)組中重復(fù)項(xiàng)功能詳解
這篇文章主要介紹了JS基于對象的特性實(shí)現(xiàn)去除數(shù)組中重復(fù)項(xiàng)功能,結(jié)合實(shí)例形式較為詳細(xì)的分析了js基于key值唯一性實(shí)現(xiàn)數(shù)組去重的具體步驟與相關(guān)操作技巧,需要的朋友可以參考下2017-11-11