2010-05-20 12 views

risposta

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

Grazie! Originariamente avevo 'if (currentMonth <9) {currentMonth =" 0 "+ currentMonth; } 'e non ha funzionato. Suppongo di aver bisogno di virgolette singole invece di doppie. –

+0

Dispari .. il tipo di preventivo non dovrebbe importare! Forse un artefatto di tipo coercizione e l'operatore '+'. – Matt

+1

Vuoi '<10' else 9 non restituire '09' –

47

Un modo alternativo:

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

+1 perché ti ho copiato per parte della mia risposta. – eyelidlessness

+1

+1 per l'eleganza –

+0

Grazie ragazzi! :) –

0

Affinché la risposta accettata per restituire una stringa in modo coerente, si dovrebbe essere:

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

Oppure:

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

Solo per funsies, ecco una versione senza condizionale:

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

Edit: passato a slice, per la risposta di Gert G, credito quando il credito è dovuto; substr lavora troppo, non mi rendevo conto che accetta un negativo start argomento

0

per la data:

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

e simili per il mese: soluzione

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

Una linea:

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 versione ispirate ai lunghi capelli da @ Gert-Grenander

let date = new Date(); 
let month = date.getMonth() +1; 
month = (`0${month}`).slice(-2); 
Problemi correlati