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

JavaScript實現Date()日期格式化的3種常用方法

 更新時間:2024年05月16日 10:58:55   作者:Seven_正在敲打鍵盤  
Date()日期對象是一個構造函數,必須使用new來調用創(chuàng)建我們的日期對象,下面這篇文章主要給大家介紹了關于JavaScript實現Date()日期格式化的3種常用方法,需要的朋友可以參考下

Date( ) 介紹

Date( ) 基本使用

Date()日期對象是構造函數,必須使用new來調用我們的日期對象。

  • Date()沒有參數時 返回當前時間
  • Date(timer)有參數時 返回參數設置的時間
    • 參數寫法:'2012-2-2 08:54:32'(字符串)
    • 返回值格式:Sun May 28 2023 23:36:28 GMT+0800 (中國標準時間)
    // 無參數時
    let dateW = new Date();
    console.log('當前時間', dateW); // Sun May 28 2023 23:36:28 GMT+0800 (中國標準時間)
    // 有參數時
    let dateY = new Date('2012-2-2 08:54:32');
    console.log('指定時間', dateY); // Thu Feb 02 2012 08:54:32 GMT+0800 (中國標準時間)

Date() 常用API

Date() 可以通過許多方法獲取日期和時間的各個部分,在格式化時間時我們經常用到這些API。

    let date = new Date();
    console.log(date.getFullYear()); //當前日期的年 2022
    console.log(date.getMonth() + 1); //月份+1 由于月份是0-11計算 所以需要 +1 
    console.log(date.getDate()); // 日
    console.log(date.getDay()); // 星期幾  注意:星期日返回的是0
    console.log(date.getHours()); // 時
    console.log(date.getMinutes()); // 分
    console.log(date.getSeconds()); // 秒

日期格式化

1.1 toLocaleString(原生方法)

Date 對象有一個 toLocaleString 方法,該方法可以格式化日期和時間,同時衍生出另外兩種分別獲得日期和時間的方法。

  • 字段說明:

    • 日期+時間: toLocaleString()
    • 日期: toLocaleDateString()
    • 時間: toLocaleTimeString()
  • 參數說明 (非必填)

    • 'en-US', { timeZone: 'America/New_York' }
    • en-US : 地區(qū)設置(String)
    • { timeZone: 'America/New_York' }: 日期時間格式和時區(qū)信息(Object)
    let timer = new Date()
    console.log(timer.toLocaleString()) // 日期+時間 2023/5/28 23:07:35
    console.log(timer.toLocaleDateString()) // 日期 2023/5/28 
    console.log(timer.toLocaleTimeString()) // 時間 23:10:31 
    // 兩個參數:(地區(qū)設置,日期時間格式和時區(qū)信息)
    console.log(time.toLocaleString('en-US', { timeZone: 'America/New_York' }))
    // 打印結果 5/28/2023, 11:08:39 AM

1.2 字符串方法

string.padStart(字符串長度, 填充元素) : 用填充元素填充string字符串,使得產生的新字符串達到所設置的長度(參數一:字符串長度)。

  • padStart 從原字符串左側開始填充
  • padEnd 從原字符串右側開始填充
    let str = 'str'
    str.padStart(5,'0') // "00str"
    
    // 不指定填充元素時,以空字符串填充
    str.padStart(5) // "  abc" 
    // 填充元素超出指定長度時,從左->右對填充元素截取
    str.padStart(6,'123465'); // "123str"
    // 原字符串長度大于設定長度時,以原字符串長度為準 不截斷原字符串
    str.padStart(2); // "str"

1) 利用字符串進行日期格式化

  console.log(time.getFullYear().toString().padStart(4, '0')) // 年 2023
  console.log((time.getMonth() + 1).toString().padStart(2, '0')) // 月 05
  console.log(time.getDate().toString().padStart(2, '0')) // 日 29
  console.log('星期' + (time.getDay() === 0 ? 7 : time.getDay())) // 周 星期1
  console.log(time.getHours().toString().padStart(2, '0')) // 時 01
  console.log(time.getMinutes().toString().padStart(2, '0')) // 分 19
  console.log(time.getSeconds().toString().padStart(2, '0')) // 秒 55

2) 格式化函數封裝

    let time = new Date()
    // 定義格式化封裝函數
    function formaData(timer) {
        const year = timer.getFullYear()
        const month = timer.getMonth() + 1 // 由于月份從0開始,因此需加1
        const day = timer.getDate()
        const hour = timer.getHours()
        const minute = timer.getMinutes()
        const second = timer.getSeconds()
        return `${pad(year, 4)}-${pad(month)}-${pad(day)} ${pad(hour)}:${pad(minute)}:${pad(second)}`
    }
    // 定義具體處理標準
    // timeEl 傳遞過來具體的數值:年月日時分秒
    // total 字符串總長度 默認值為2
    // str 補充元素 默認值為"0"
    function pad(timeEl, total = 2, str = '0') {
        return timeEl.toString().padStart(total, str)
    }
    // 調用函數
    console.log(formaData(time)) // 2023-05-29 00:30:19

1.3 第三方庫

除了以上方法外,還有很多第三方庫可以用來格式化日期時間,最常用的主要為 Moment.js。

1)安裝 Moment.js

    npm install moment

2)導入 Moment.js 模塊(main.js)

    import moment from 'moment';
    Vue.prototype.$moment = moment

3)格式化時間

// `this.$moment()` 輸出當前時間的moment對象
console.log(this.$moment().format('YYYY-MM-DD HH:mm:ss')); // 2023-05-29 00:30:19

其他處理方法

2.1 時間戳

date 時間戳(毫秒數):

  • 獲取date總的毫秒數,不是當前時間的毫秒數,而是距離1970年1月1日過了多少毫秒數。

  • 獲取方法:

    • valueof( ) 、 getTime( )
    • const timer = + new Date() 常用
    • Date.now( ) 低版本瀏覽器打不開
    let date = new Date();
    // 寫法一
    console.log(date.valueOf()); //現在時間距離1970.1.1的毫秒數
    console.log(date.getTime());
    
    // 寫法二
    let date = +new Date(); 
    console.log(date); //返回當前總的毫秒數
    
    // 寫法三
     console.log(Date.now()); // H5新增 低版本瀏覽器打不開
    

倒計時函數封裝

    function countDown(time) {
        let dateNow = +new Date(); // 獲取當前時間的毫秒數
        let dateOver = +new Date(time); // 獲取目標時間的毫秒數
        let gapTime = (dateOver - dateNow) / 1000 // 由毫秒得到秒
        let s = pad(parseInt(gapTime % 60)); // 秒數
        let m = pad(parseInt(gapTime / 60 % 60)); // 分鐘數
        let h = pad(parseInt(gapTime / 60 / 60 % 24)); // 小時數
        let d = pad(parseInt(cha / 60 / 60 / 24)); // 天數
        return d + '天' + h + '小時' + m + '分鐘' + s + '秒';
    }
    
    // 時間標準的處理函數
    function pad(timeEl, total = 2, str = '0') {
        return timeEl.toString().padStart(total, str)
    }
    
    // 調用函數
    console.log(countDown('2122-5-19 8:00:00'));

匯總一下new Date().getxxx/setxxx的方法輸出,簡述一些注意點:

  • new Date(param)param可以有幾種格式,有瀏覽器通用的年月日時分秒的格式,但也會有IE,safari可能不兼容的格式,報錯invalid date
  • getYear()方法返回的是年份的后兩位,但這是1970-1999年才是兩位,2000-???則一直加上去,會出現三位以上的返回,2000就是100,依次類推…
  • getMonth()返回的是0-11的數值,0是一月Jan,所以輸出的時候需要注意+1;同理getDay()返回0-6,0代表星期日Sun;
  • getTime()返回的是1970.1.1開始到現在的毫秒數,同理valueof()也是一樣的,注意Date.parse(new Date()返回的也是毫秒數,但會將后三位讀取為0,不建議使用;
  • 對于不存在的日期格式,就如new Date(yyyy,mth,dd,hh,mm,ss)中除了yyyy之外其他如果超過其取值范圍的話,會像其’上級’進制,如ss(0-59)如果寫著65,那就用65減去 [區(qū)間位60],的05并像其’上級’,mm進一位,表達不好可以看例子…
        /*
        * js中單獨調用new Date();  顯示這種格式  Wed Jul 31 2019 13:20:09 GMT+0800 (中國標準時間)
        * 但是用new Date() 參與計算會自動轉換為從1970.1.1開始的毫秒數
        */
        var current_date = new Date(); // Wed Jan 24 2019 13:20:09 GMT+0800 (中國標準時間)
        var before_date = new Date("1991/2/25 11:59:05"); // Mon Feb 25 1991 11:59:05 GMT+0800 (中國標準時間)
        var demo_date = new Date(667454345000); // Mon Feb 25 1991 11:59:05 GMT+0800 (中國標準時間)
        // 對于輸入超過取值范圍的參數,實行上級進位制
        var error_date = new Date(2018,13,25,13,56,08);
        var error_date1 = new Date(2018,1,30,13,56,08);
        console.log(error_date); // mth(0-11) 區(qū)間位12  Mon Feb 25 2019 13:56:08 GMT+0800
        console.log(error_date1); // dd(閏年1-29|平年1-28) 2018區(qū)間位28 Fri Mar 02 2018 13:56:08 GMT+0800
        ---------------------------------------------------------------------------------------

        // getxxx獲取的數值number格式:
        before_date.getYear(); //  91   1970-1999獲取當前年份(2位) 
        current_date.getYear(); //  119   2000-????獲取3位以上就是一直算上去 2000年剛好為100
        before_date.getFullYear(); //  1991  獲取完整的年份(4位,1970-????)  
        before_date.getMonth(); //  1  獲取當前月份(0-11,0代表1月),所以獲取當前月份是before_date.getMonth()+1;   
        before_date.getDate(); //  25  獲取當前日(1-31)  
        before_date.getDay(); //  1  獲取當前星期X(0-6,0代表星期天)  
        before_date.getTime(); // 667454345000  獲取當前時間(從1970.1.1開始的毫秒數) 
        before_date.valueOf(); // 667554345000 同上
        before_date.getHours(); // 11  獲取當前小時數(0-23)  
        before_date.getMinutes(); //   59  獲取當前分鐘數(0-59)  
        before_date.getSeconds(); //  5   獲取當前秒數(0-59)  
        current_date.getMilliseconds(); // 獲取當前毫秒數(0-999)
        ----------------------------------------------------------------------------------------
        // 設置setxxx
        setDate() // 設置 Date 對象中月的某一天 (1 ~ 31)
		setMonth() // 設置 Date 對象中月份 (0 ~ 11)
		setFullYear() // 設置 Date 對象中的年份(四位數字)
		setFullYear() // setYear()方法已經淘汰
		setHours() // 設置 Date 對象中的小時 (0 ~ 23)
		setMinutes() // 設置 Date 對象中的分鐘 (0 ~ 59)
		setSeconds() // 設置 Date 對象中的秒鐘 (0 ~ 59)
		setMilliseconds() // 設置 Date 對象中的毫秒 (0 ~ 999)
		setTime() // 以毫秒設置 Date 對象
		setUTCDate() // 根據世界時設置 Date 對象中月份的一天 (1 ~ 31)
		setUTCMonth() // 根據世界時設置 Date 對象中的月份 (0 ~ 11)
		setUTCFullYear() // 根據世界時設置 Date 對象中的年份(四位數字)
		setUTCHours() // 根據世界時設置 Date 對象中的小時 (0 ~ 23)
		setUTCMinutes() // 根據世界時設置 Date 對象中的分鐘 (0 ~ 59)
		setUTCSeconds() // 根據世界時設置 Date 對象中的秒鐘 (0 ~ 59)
		setUTCMilliseconds() // 根據世界時設置 Date 對象中的毫秒 (0 ~ 999)

匯總一下new Date().toxxx/toLocalexxx的方法輸出,簡述一些注意點:

  • toDateString/toTimeString || toLocaleDateString/toLocaleTimeString兩者的輸出文本格式有所差異,且后者新增的參數 locales 和 options 使程序能夠指定使用哪種語言格式化規(guī)則
  • toGMTString、toUTCString兩者在定義上只是名字有所差異,其實GMT在時間數值上是接近UTC的,他們輸出的格式一樣,是標準時間
  • toLocaleString方法在不同瀏覽器輸出的文本格式不同,我們可以自定義一個統一的輸出
 // 返回字符串string格式:
        current_date.toLocaleDateString(); // yyyy/MM/dd  獲取當前日期  
        current_date.toLocaleTimeString(); // (上午/下午) hh:mm:ss  獲取當前時間
        current_date.toLocaleString( ); // 獲取日期與時間 
//  ————————————————————————————————–————————————————————————————————–
// 1、當前系統區(qū)域設置格式(toLocaleDateString和toLocaleTimeString)
     例子:(new Date()).toLocaleDateString() + " " + (new Date()).toLocaleTimeString()
     結果: 2008年1月29日 16:13:11
// 2.普通字符串(toDateString和toTimeString)
     例子: (new Date()).toDateString() + " " + (new Date()).toTimeString()
     結果:Tue Jan 29 2008 16:13:11 UTC+0800
// 3.格林威治標準時間(toGMTString)
     例子: (new Date()).toGMTString()
     結果:Tue, 29 Jan 2008 08:13:11 UTC
// 4.全球標準時間(toUTCString)
     例子: (new Date()).toUTCString()
     結果:Tue, 29 Jan 2008 08:13:11 UTC
// 5.Date對象字符串(toString)
     例子: (new Date()).toString()
     結果:Tue Jan 29 16:13:11 UTC+0800 2008
// ————————————————————————————————–————————————————————————————————–

總結 

到此這篇關于JavaScript實現Date()日期格式化的3種常用方法的文章就介紹到這了,更多相關JS實現Date()日期格式化內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論