2012-02-01 15 views
5

ho il seguente codice per ottenere il giorno corrente:Come ottenere l'ultimo giorno del mese precedente in Javascript o JQuery

var month=new Array(12); 
month[0]="January"; 
month[1]="February"; 
month[2]="March"; 
month[3]="April"; 
month[4]="May"; 
month[5]="June"; 
month[6]="July"; 
month[7]="August"; 
month[8]="September"; 
month[9]="October"; 
month[10]="November"; 
month[11]="December"; 

var d = new Date(); 
var curr_date; 
if (d.getDate() == 1) 
{ 
    curr_date = d.getDate(); 
} 
else 
{ 
    curr_date = d.getDate() - 1; 
} 

var curr_month = d.getMonth() + 1; //months are zero based 
var curr_year = d.getFullYear(); 
var message_day = curr_year + "_" + curr_month + "_" + curr_date; 
var sql_day = month[curr_month - 1].substring(0,3) + curr_date.toString() + curr_year.toString(); 

if (curr_date == "1") 
    { 
     document.write(sql_day + " " + message_day); 
    } 

Questo è grande per ottenere il giorno in corso, ma ora ho bisogno di ottenere l'ultimo giorno dell'ultimo mese se è l'inizio di un nuovo mese.

adesso questo produrrà:

Feb12012 2012_2_1 

ma che cosa ho bisogno di uscita è:

Jan312012 2012_1_31 

Grazie

risposta

14
var d=new Date(); // current date 
d.setDate(1); // going to 1st of the month 
d.setHours(-1); // going to last hour before this date even started. 

ora d contiene l'ultima data del mese precedente. d.getMonth() e d.getDate() lo rifletteranno.

Questo dovrebbe funzionare su qualsiasi data api che avvolge c time.h. Vedere this

+0

Grazie, ha funzionato molto bene. –

1

Basta sottrarre uno dal giorno del mese:

var today = new Date(); 
var yesterday = new Date().setDate(today.getDate() - 1); 

Se la "d mangiato "proprietà (il giorno del mese) è 1, quindi impostandolo su zero si otterrà una data che rappresenta l'ultimo giorno del mese precedente. Il tuo codice era già abbastanza vicino; si può solo costruire una nuova istanza Data:

if (d.getDate() === 1) 
    curr_date = new Date().setDate(0).getDate(); 

In realtà non hanno nemmeno bisogno di un "if":

curr_date = new Date().setDate(d.getDate() - 1).getDate(); 

e che sarà il lavoro per tutti i giorni del mese.

+0

per qualche motivo, non sto ottenendo l'output che mi aspetto: http://jsfiddle.net/gT6eZ/1/ –

11

Questo funziona perfettamente per me:

var date = new Date(); 
date.setDate(0); 

data ora contiene l'ultimo giorno del mese precedente.

Problemi correlati