前端常見的時間轉(zhuǎn)換方法以及獲取當前時間方法小結(jié)
更新時間:2024年01月22日 15:22:17 作者:起名時在學Aiifox
在做開發(fā)時會對不同的時間格式進行轉(zhuǎn)換,下面這篇文章主要給大家介紹了關(guān)于前端常見的時間轉(zhuǎn)換方法以及獲取當前時間方法的相關(guān)資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
1、獲取當前年月日時間
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'); // 補零
const minutes = date.getMinutes().toString().padStart(2, '0'); // 補零
this.currentDate = `${year}-${month}.${day}-${hours}:${minutes}`;
},2、將時間戳轉(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中時間轉(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)換的時間').format('YYYY-MM-DD') 

總結(jié)
到此這篇關(guān)于前端常見的時間轉(zhuǎn)換方法以及獲取當前時間方法的文章就介紹到這了,更多相關(guān)前端時間轉(zhuǎn)換及獲取當前時間內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
微信小程序bindtap與catchtap的區(qū)別詳解
本文主要介紹了微信小程序bindtap與catchtap的區(qū)別詳解,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09
根據(jù)輸入郵箱號跳轉(zhuǎn)到相應(yīng)登錄地址的解決方法
本文分享了基于javascript實現(xiàn)的根據(jù)輸入郵箱號跳轉(zhuǎn)到相應(yīng)登錄地址的具體實例代碼,需要的朋友一起來看下吧2016-12-12
根據(jù)地區(qū)不同顯示時間的javascript代碼
根據(jù)地區(qū)不同顯示時間的javascript代碼...2007-08-08
JS基于對象的特性實現(xiàn)去除數(shù)組中重復(fù)項功能詳解
這篇文章主要介紹了JS基于對象的特性實現(xiàn)去除數(shù)組中重復(fù)項功能,結(jié)合實例形式較為詳細的分析了js基于key值唯一性實現(xiàn)數(shù)組去重的具體步驟與相關(guān)操作技巧,需要的朋友可以參考下2017-11-11

