關於new Date()獲取當前時間

在我們使用new Date() 想要獲取當前時間時,但是格式不是我們想要的,比如格式爲 年-月-日,可以使用如下方法:

const date = new Date();

 const  current_date = date.getDate();
    // 獲取本  日
 const  current_month = date.getMonth() + 1;
    // 獲取本  月
 const  current_year = date.getFullYear();
    // 獲取本  年

這裏獲取本月爲什麼 要 + 1 呢,很簡單,因爲是按數組下標算起的,如本月爲8月,它的下標就爲7,所以要加1,

month=[ 0, ....,11]。

這樣我們就可以拼接成我們想要的樣子了:

console.log('-----------------------------------------------------');
console.log(current_year + '-' + current_month + '-' + current_date);
console.log('-----------------------------------------------------');

打印後是這樣:

如有更好的辦法,歡迎隨時指出。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章