JavaScript時間格式化函數(shù)功能及使用示例
更新時間:2023年11月21日 09:00:54 投稿:ychy
這篇文章主要為大家介紹了JavaScript時間格式化函數(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' /* 獲取時間戳 */:
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)前時間戳以上就是JavaScript時間格式化函數(shù)功能及使用示例的詳細內(nèi)容,更多關(guān)于JavaScript時間格式化函數(shù)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
一文詳解preact的高性能狀態(tài)管理Signals
這篇文章主要介紹了一文詳解preact的高性能狀態(tài)管理Signals,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,感興趣的朋友可以參考一下2022-09-09
JS開發(fā)中基本數(shù)據(jù)類型具體有哪幾種
JS的數(shù)據(jù)類型包括基本數(shù)據(jù)類型、復(fù)雜數(shù)據(jù)類型和特殊數(shù)據(jù)類型,今天我們主要先講解一下基本數(shù)據(jù)類型。感興趣的朋友一起看看吧2017-10-10
重置Redux的狀態(tài)數(shù)據(jù)的方法實現(xiàn)
這篇文章主要介紹了重置Redux的狀態(tài)數(shù)據(jù)的方法實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
uni-app封裝組件實現(xiàn)下方滑動彈出模態(tài)框效果
這篇文章主要介紹了uni-app封裝組件實現(xiàn)下方滑動彈出模態(tài)框效果,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-08-08

