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ù)的資料請關(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)用,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-03-03JavaScript 自動(dòng)分號插入(JavaScript synat:auto semicolon insertion)
今天在看《Extjs中文手冊》的時(shí)候,寫了四五行樣例代碼,結(jié)果IE和Firefox一直報(bào)錯(cuò)不通過。2009-11-11JavaScript函數(shù)及其prototype詳解
這篇文章主要介紹了JavaScript函數(shù)及其prototype詳解的相關(guān)資料,需要的朋友可以參考下2023-03-03將中國標(biāo)準(zhǔn)時(shí)間轉(zhuǎn)換成標(biāo)準(zhǔn)格式的代碼
這篇文章主要介紹了將中國標(biāo)準(zhǔn)時(shí)間轉(zhuǎn)換成標(biāo)準(zhǔn)格式的方法,需要的朋友可以參考下2014-03-03javascript實(shí)現(xiàn)簡單的鼠標(biāo)拖動(dòng)效果實(shí)例
這篇文章主要介紹了javascript實(shí)現(xiàn)簡單的鼠標(biāo)拖動(dòng)效果,實(shí)例分析了javascript鼠標(biāo)拖動(dòng)效果的相關(guān)要點(diǎn)與實(shí)現(xiàn)技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04