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對(duì)大量數(shù)據(jù)進(jìn)行多重過濾的方法
今天在工作中遇到一個(gè)問題,當(dāng)前端通過Ajax從后端取得了大量的數(shù)據(jù),需要根據(jù)一些條件過濾,但是發(fā)現(xiàn)寫的過濾方法有問題,后來仔細(xì)的查找問題,通過網(wǎng)上的資料終于解決了這個(gè)問題,現(xiàn)在將解決的過程以及解決方法分享給大家,有需要的朋友們可以參考借鑒。2016-11-11
JS使用JSON.parse(),JSON.stringify()實(shí)現(xiàn)對(duì)對(duì)象的深拷貝功能分析
這篇文章主要介紹了JS使用JSON.parse(),JSON.stringify()實(shí)現(xiàn)對(duì)對(duì)象的深拷貝功能,結(jié)合實(shí)例形式分析了JSON.parse()與JSON.stringify()方法實(shí)現(xiàn)深拷貝的相關(guān)實(shí)現(xiàn)技巧與操作注意事項(xiàng),需要的朋友可以參考下2019-03-03
JavaScript Window窗口對(duì)象屬性和使用方法
這篇文章主要介紹了JavaScript Window窗口對(duì)象屬性和使用方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01
使用HTML+JavaScript實(shí)現(xiàn)SQL智能補(bǔ)全功能
現(xiàn)代數(shù)據(jù)庫(kù)管理工具中,SQL 智能補(bǔ)全功能已成為提升開發(fā)效率的重要特性,它能夠根據(jù)上下文環(huán)境自動(dòng)提示關(guān)鍵詞、表名、字段名等信息,大大減少了手動(dòng)輸入錯(cuò)誤和查詢文檔的時(shí)間,本文將介紹如何使用HTML、CSS和JavaScript實(shí)現(xiàn)SQL智能補(bǔ)全功能,需要的朋友可以參考下2026-03-03
JS中利用localStorage防止頁(yè)面動(dòng)態(tài)添加數(shù)據(jù)刷新后數(shù)據(jù)丟失
本文給大家分享一段js代碼利用利用localStorage防止頁(yè)面動(dòng)態(tài)添加數(shù)據(jù)刷新后數(shù)據(jù)丟失問題,代碼簡(jiǎn)單易懂,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下2017-03-03

