2010-05-20 12 views

Odpowiedz

17
if (currentMonth < 10) { currentMonth = '0' + currentMonth; } 
+0

Dzięki! Pierwotnie miałem 'if (currentMonth <9) {currentMonth =" 0 "+ currentMonth; } 'i to nie działało. Chyba potrzebuję pojedynczych cudzysłowów zamiast podwójnych. –

+0

Nieparzysta .. rodzaj cytatu nie powinien mieć znaczenia! Może artefakt typu przymusu i operatora '+' .. – Matt

+1

Chcesz "<10" jeszcze 9 nie zwróci "09" –

47

Alternatywnym sposobem:

var currentMonth=('0'+(currentDate.getMonth()+1)).slice(-2) 
+1

+1, ponieważ skopiowałem Cię na część mojej odpowiedzi. – eyelidlessness

+1

+1 za elegancję –

+0

Dzięki chłopaki! :) –

0

Aby zaakceptowanej odpowiedzi zwraca ciąg konsekwentnie go powinno być:

if(currentMonth < 10) { 
    currentMonth = '0' + currentMonth; 
} else { 
    currentMonth = '' + currentMonth; 
} 

Lub:

currentMonth = (currentMonth < 10 ? '0' : '') + currentMonth; 

Tylko dla funsies, oto wersja bez warunkowego:

currentMonth = ('0' + currentMonth).slice(-2); 

Edit: przełączony slice, za Gert G odpowiedź kredytu w przypadku gdy kredyt jest wymagalna; substr działa zbyt, nie zdawałem sobie sprawy, że akceptuje negatywny start argumentu

0

na dzień:

("0" + this.getDate()).slice(-2) 

i podobny do miesiąca: Rozwiązanie

("0" + (this.getMonth() + 1)).slice(-2) 
3

Jedna linia:

var currentMonth = (currentDate.getMonth() < 10 ? '0' : '') + currentDate.getMonth(); 
0
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); 
0

ES6 wersja inpired przez @ Gert-grenander

let date = new Date(); 
let month = date.getMonth() +1; 
month = (`0${month}`).slice(-2); 
Powiązane problemy