如何從mm
格式的當前日期檢索月份? (即 「05」)以mm格式在javascript中獲取月份
這是我當前的代碼:
var currentDate = new Date();
var currentMonth = currentDate.getMonth() + 1;
如何從mm
格式的當前日期檢索月份? (即 「05」)以mm格式在javascript中獲取月份
這是我當前的代碼:
var currentDate = new Date();
var currentMonth = currentDate.getMonth() + 1;
if (currentMonth < 10) { currentMonth = '0' + currentMonth; }
的另一種方法:
var currentMonth=('0'+(currentDate.getMonth()+1)).slice(-2)
+1因爲我複製了你的部分答案。 – eyelidlessness 2010-05-20 22:29:48
+1爲優雅 – 2010-05-21 06:24:00
謝謝你們! :) – 2010-05-21 13:34:38
爲了接受的答案始終如一地返回一個字符串,它應該是:
if(currentMonth < 10) {
currentMonth = '0' + currentMonth;
} else {
currentMonth = '' + currentMonth;
}
或者:
currentMonth = (currentMonth < 10 ? '0' : '') + currentMonth;
只是爲了funsies,這裏是沒有條件的一個版本:
currentMonth = ('0' + currentMonth).slice(-2);
編輯:切換到slice
,每格特G公司的回答,信貸,信貸是由於; substr
工作過,我不知道它接受一個負start
參數
如果你這樣做
var currentDate = new Date();
var currentMonth = currentDate.getMonth() + 1;
然後currentMonth是一個數字,你可以格式化,只要你想,看到了這個問題,這將有助於你與格式:How can I format an integer to a specific length in javascript?
的日期:
("0" + this.getDate()).slice(-2)
和類似月:
("0" + (this.getMonth() + 1)).slice(-2)
一號線的解決方案:
var currentMonth = (currentDate.getMonth() < 10 ? '0' : '') + currentDate.getMonth();
var CurrentDate = new Date();
CurrentDate.setMonth(CurrentDate.getMonth());
var day = CurrentDate.getDate();
var monthIndex = CurrentDate.getMonth()+1;
if(monthIndex<10){
monthIndex=('0'+monthIndex);
}
var year = CurrentDate.getFullYear();
alert(monthIndex);
ES6版本 inpired通過@格特 - grenander
let date = new Date();
let month = date.getMonth() +1;
month = (`0${month}`).slice(-2);
謝謝!我原本有'if(currentMonth <9){currentMonth =「0」+ currentMonth; }'並沒有工作。猜猜我需要單引號而不是雙引號。 – 2010-05-20 22:07:47
奇怪..報價類型不重要!也許類型強制和'+'經營者的神器.. – Matt 2010-05-20 22:09:14
你想'<10'其他9不會返回「09」 – 2010-05-20 22:09:17