2009-12-17 30 views

Respuesta

23

Esto le dará último día del mes en curso.

var t= new Date(); 
alert(new Date(t.getFullYear(), t.getMonth() + 1, 0, 23, 59, 59)); 
+1

No hay necesidad de dos objetos Date: 't.setMonths (t.getMonth() + 1, 0, 23, 59, 59 , 0) '. – RobG

35
function LastDayOfMonth(Year, Month) { 
    return new Date((new Date(Year, Month,1))-1); 
} 

Ejemplo:

> LastDayOfMonth(2009, 11) 
Mon Nov 30 2009 23:59:59 GMT+0100 (CET) 
+1

1, pero establece el tiempo a 23: 59: 59.999. Quizás sea mejor establecer segundos a 59,000 entonces '... Mes, 1)) - 1000)'. :-) – RobG

+2

No puedo imaginar por qué querrías dejar 999ms fuera del cálculo de rango – jcollum

0
Calendar cal = Calendar.getInstance(); 
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE)); 

Date lastDayOfMonth = cal.getTime(); 
+7

Eso es un javascript extraño que tienes allí. – droope

0
var d = new Date(); 
m = d.getMonth(); //current month 
y = d.getFullYear(); //current year 
alert(new Date(y,m,1)); //this is first day of current month 
alert(new Date(y,m+1,0)); //this is last day of current month 
+0

He intentado esto, y 'alerta (nueva Fecha (y, m + 1,0));' te da el último día del mes siguiente. – mickburkejnr

4
var d = new Date(); 
console.log(d); 
d.setMonth(d.getMonth() + 1); // set month as next month 
console.log(d); 
d.setDate(0); // get the last day of previous month 
console.log(d); 

Aquí se emite desde el código anterior:
Mar Oct 03 2013 11:34:59 GMT + 0100 (GMT horario)
Dom Nov 03 2013 11 : 34: 59 GMT + 0000 (GMT Standard Time)
Thu 31 de octubre 2013 11:34:59 GMT + 0000 (GMT hora estándar)

+0

Puede simplificar esto un poco más pasando la fecha a 'setMonth' como así:' d.setMonth (d.getMonth() + 1, 0) ' – Jared

1
var month = 1; // 1 for January 
var d = new Date(2015, month, 0); 
console.log(d); // last day in January 
1

A veces todo lo que tienes es una versión de texto del mes en curso, es decir: April 2017.

//first and last of the current month 
var current_month = "April 2017"; 
var arrMonth = current_month.split(" "); 
var first_day = new Date(arrMonth[0] + " 1 " + arrMonth[1]); 

//even though I already have the values, I'm using date functions to get year and month 
//because month is zero-based 
var last_day = new Date(first_day.getFullYear(), first_day.getMonth() + 1, 0, 23, 59, 59); 

//use moment,js to format  
var start = moment(first_day).format("YYYY-MM-DD"); 
var end = moment(last_day).format("YYYY-MM-DD"); 
Cuestiones relacionadas