JavaScript時(shí)間格式化函數(shù)功能及使用示例
功能
- 獲取時(shí)間戳
- 格式化時(shí)間
完整代碼
// _date 為需要格式化的日期,format 為需要格式化的樣式
function formatDate(_date, format) {
const date = new Date(_date);
switch (format) {
case 'yyyy':
return date.getFullYear();
case 'yy':
return ('' + date.getFullYear).slice(-2);
case 'M':
return date.getMonth() + 1;
case 'MM':
return ('0' + (date.getMonth() + 1) ).slice(-2);
case 'd':
return date.getDate();
case 'dd':
return ('0' + date.getDate()).slice(-2);
case 'H':
return date.getHours();
case 'HH':
return ('0' + date.getHours()).slice(-2);
case 'h':
return date.getHours() % 12;
case 'hh':
return ('0' + date.getHours()).slice(-2);
case 'm':
return date.getMinutes();
case 'mm':
return ('0' + date.getMinutes()).slice(-2);
case 's':
return date.getSeconds();
case 'ss':
return ('0' + date.getSeconds()).slice(-2);
case 'w':
return ['日', '一', '二', '三', '四', '五', '六'][date.getDay()];
case 'stamp' /* 獲取時(shí)間戳 */:
return Date.now();
default:
return;
}
}使用
console.log(formatDate(new Date('2021-01-02'), 'w')); // 六
console.log(formatDate(new Date(), 'w')); // 二
console.log(formatDate('2021-01-02', 'w')); //六
console.log(formatDate('2021/01/02', 'w')); //六
console.log(formatDate(Date.now(), 'w')); //六
console.log(formatDate(new Date(), 'stamp')); // 輸出當(dāng)前時(shí)間戳以上就是JavaScript時(shí)間格式化函數(shù)功能及使用示例的詳細(xì)內(nèi)容,更多關(guān)于JavaScript時(shí)間格式化函數(shù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
解決JS浮點(diǎn)數(shù)運(yùn)算出現(xiàn)Bug的方法
解決JS浮點(diǎn)數(shù)運(yùn)算出現(xiàn)Bug的方法,需要的朋友可以參考一下2013-03-03
一文詳解preact的高性能狀態(tài)管理Signals
這篇文章主要介紹了一文詳解preact的高性能狀態(tài)管理Signals,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,感興趣的朋友可以參考一下2022-09-09
JavaScript數(shù)組實(shí)例的9個(gè)方法
這篇文章主要介紹了JavaScript數(shù)組實(shí)例的9個(gè)方法,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹沒(méi)具有一定的參考價(jià)值,需要的朋友可以參考一下2022-07-07
JS開(kāi)發(fā)中基本數(shù)據(jù)類型具體有哪幾種
JS的數(shù)據(jù)類型包括基本數(shù)據(jù)類型、復(fù)雜數(shù)據(jù)類型和特殊數(shù)據(jù)類型,今天我們主要先講解一下基本數(shù)據(jù)類型。感興趣的朋友一起看看吧2017-10-10
JavaScript返回0-1之間隨機(jī)數(shù)的方法
這篇文章主要介紹了JavaScript返回0-1之間隨機(jī)數(shù)的方法,涉及javascript中Math對(duì)象random方法的使用技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04
重置Redux的狀態(tài)數(shù)據(jù)的方法實(shí)現(xiàn)
這篇文章主要介紹了重置Redux的狀態(tài)數(shù)據(jù)的方法實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
uni-app封裝組件實(shí)現(xiàn)下方滑動(dòng)彈出模態(tài)框效果
這篇文章主要介紹了uni-app封裝組件實(shí)現(xiàn)下方滑動(dòng)彈出模態(tài)框效果,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2024-08-08

