欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript時(shí)間格式化函數(shù)功能及使用示例

 更新時(shí)間:2023年11月21日 09:00:54   投稿:ychy  
這篇文章主要為大家介紹了JavaScript時(shí)間格式化函數(shù)功能及使用示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

功能

  • 獲取時(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)文章

最新評論