Jak mogę pobrać miesiąc z bieżącej daty w formacie mm
? (Czyli "05")Pobierz miesiąc w formacie mm w javascript
To jest mój bieżący kod:
var currentDate = new Date();
var currentMonth = currentDate.getMonth() + 1;
Jak mogę pobrać miesiąc z bieżącej daty w formacie mm
? (Czyli "05")Pobierz miesiąc w formacie mm w javascript
To jest mój bieżący kod:
var currentDate = new Date();
var currentMonth = currentDate.getMonth() + 1;
if (currentMonth < 10) { currentMonth = '0' + currentMonth; }
Alternatywnym sposobem:
var currentMonth=('0'+(currentDate.getMonth()+1)).slice(-2)
+1, ponieważ skopiowałem Cię na część mojej odpowiedzi. – eyelidlessness
+1 za elegancję –
Dzięki chłopaki! :) –
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
Jeśli zrobisz to
var currentDate = new Date();
var currentMonth = currentDate.getMonth() + 1;
następnie currentMonth jest liczbą, którą można sformatować, jak chcesz, patrz na to pytanie, które pomogą Ci z formatowaniem: How can I format an integer to a specific length in javascript?
na dzień:
("0" + this.getDate()).slice(-2)
i podobny do miesiąca: Rozwiązanie
("0" + (this.getMonth() + 1)).slice(-2)
Jedna linia:
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 wersja inpired przez @ Gert-grenander
let date = new Date();
let month = date.getMonth() +1;
month = (`0${month}`).slice(-2);
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. –
Nieparzysta .. rodzaj cytatu nie powinien mieć znaczenia! Może artefakt typu przymusu i operatora '+' .. – Matt
Chcesz "<10" jeszcze 9 nie zwróci "09" –