¿Cómo sumar/restar fechas con JavaScript?

Quiero que los usuarios puedan añadir y restar fechas fácilmente usando JavaScript para poder navegar por sus entradas por fecha.

Las fechas están en el formato: "mm/dd/aaaa". Quiero que puedan hacer clic en un botón "Siguiente", y si la fecha es: "06/01/2012" entonces al hacer clic en siguiente, debe convertirse en: "06/02/2012". Si hacen clic en el botón 'prev', entonces debería convertirse en, "31/05/2012".

Debe tener en cuenta los años bisiestos, el número de días del mes, etc.

¿Alguna idea?

P.D. usar AJAX para obtener la fecha del servidor no es una opción, es un poco lento y no es la experiencia para el usuario que el cliente quiere.

Solución

Código:

begin snippet: js hide: false console: true babel: false -->

var date = new Date('2011', '01', '02');
alert('the original date is ' + date);
var newdate = new Date(date);

newdate.setDate(newdate.getDate() - 7); // minus the date

var nd = new Date(newdate);
alert('the new date is ' + nd);

Usando Datepicker:

$("#in").datepicker({
    minDate: 0,
    onSelect: function(dateText, inst) {
       var actualDate = new Date(dateText);
       var newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate()+1);
        $('#out').datepicker('option', 'minDate', newDate );
    }
});

$("#out").datepicker();​

[JSFiddle Demo][2]

Cosas extra que pueden ser útiles:

getDate()   Returns the day of the month (from 1-31)
getDay()    Returns the day of the week (from 0-6)
getFullYear()   Returns the year (four digits)
getHours()  Returns the hour (from 0-23)
getMilliseconds()   Returns the milliseconds (from 0-999)
getMinutes()    Returns the minutes (from 0-59)
getMonth()  Returns the month (from 0-11)
getSeconds()    Returns the seconds (from 0-59)

Buen enlace: [Fecha MDN][1]

Comentarios (2)
startdate.setDate(startdate.getDate() - daysToSubtract);

startdate.setDate(startdate.getDate() + daysToAdd);
Comentarios (0)

Puedes utilizar el objeto Date nativo de javascript para hacer un seguimiento de las fechas. Te dará la fecha actual, te permitirá hacer un seguimiento de cosas específicas del calendario e incluso te ayudará a gestionar diferentes zonas horarias. Puedes añadir y restar días/horas/segundos para cambiar la fecha con la que estás trabajando o para calcular nuevas fechas.

Echa un vistazo a esta referencia de objeto para aprender más:

Fecha

Espero que le sirva de ayuda.

Comentarios (0)