JavaScript時間格式化函數(shù)功能及使用示例
更新時間:2023年11月21日 09:00:54 投稿:ychy
這篇文章主要為大家介紹了JavaScript時間格式化函數(shù)功能及使用示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
功能
- 獲取時間戳
- 格式化時間
完整代碼
// _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ù)功能及使用示例的詳細(xì)內(nèi)容,更多關(guān)于JavaScript時間格式化函數(shù)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
js中的preventDefault與stopPropagation詳解
本篇文章主要是對js中的preventDefault與stopPropagation進(jìn)行了介紹,需要的朋友可以過來參考下,希望對大家有所幫助2014-01-01詳解使用Nuxt.js快速搭建服務(wù)端渲染(SSR)應(yīng)用
這篇文章主要介紹了詳解使用Nuxt.js快速搭建服務(wù)端渲染(SSR)應(yīng)用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-03-03JavaScript 自動分號插入(JavaScript synat:auto semicolon insertion)
今天在看《Extjs中文手冊》的時候,寫了四五行樣例代碼,結(jié)果IE和Firefox一直報錯不通過。2009-11-11JavaScript函數(shù)及其prototype詳解
這篇文章主要介紹了JavaScript函數(shù)及其prototype詳解的相關(guān)資料,需要的朋友可以參考下2023-03-03將中國標(biāo)準(zhǔn)時間轉(zhuǎn)換成標(biāo)準(zhǔn)格式的代碼
這篇文章主要介紹了將中國標(biāo)準(zhǔn)時間轉(zhuǎn)換成標(biāo)準(zhǔn)格式的方法,需要的朋友可以參考下2014-03-03javascript實現(xiàn)簡單的鼠標(biāo)拖動效果實例
這篇文章主要介紹了javascript實現(xiàn)簡單的鼠標(biāo)拖動效果,實例分析了javascript鼠標(biāo)拖動效果的相關(guān)要點與實現(xiàn)技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04