JavaScript cómo obtener la fecha de mañana en formato dd-mm-aa

90

Estoy intentando que JavaScript muestre la fecha de mañana en formato (dd-mm-aaaa)

Tengo este script que muestra la fecha de hoy en formato (dd-mm-aaaa)

var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
document.write("<b>" + day + "/" + month + "/" + year + "</b>")

Displays: 25/2/2012 (todays date of this post)

Pero, ¿cómo hago para que muestre la fecha de mañana en el mismo formato? 26/2/2012

Probé esto:

var day = currentDate.getDate() + 1

Sin embargo, pude mantener +1 y superar los 31, obviamente, no hay> 32 días en un mes.

¿Ha estado buscando durante horas pero parece que no hay respuesta o solución a esto?

daza166
fuente

Respuestas:

176

Esto debería arreglarlo muy bien para ti.

Si pasa el constructor Date una vez, hará el resto del trabajo.

24 horas 60 minutos 60 segundos 1000 milisegundos

var currentDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
document.write("<b>" + day + "/" + month + "/" + year + "</b>")

Una cosa a tener en cuenta es que este método devolverá la fecha exactamente en 24 horas a partir de ahora, lo que puede ser inexacto alrededor del horario de verano.

La respuesta de Phil funciona en cualquier momento:

var currentDate = new Date();
currentDate.setDate(currentDate.getDate() + 1);

La razón por la que edité mi publicación es porque yo mismo creé un error que salió a la luz durante el horario de verano usando mi método anterior.

Roderick Obrist
fuente
9
Gracias, un poco más cortovar currentDate = new Date(+new Date() + 86400000);
Ikrom
13
Tenga en cuenta que con esta estrategia podría tener problemas relacionados con el horario de verano, lo que hace que un día del año tenga 23 horas y otro tenga 25. La respuesta de Phil a continuación evita este problema.
gsf
3
new Date().getTime()se puede simplificar comoDate.now()
czerny
Ambos son correctos, aunque no creo que IE8 tenga Date.now ().
Roderick Obrist
2
@ConorB, .getMonth () devuelve 0 para enero, 1 para febrero ... etc 11 para diciembre. Agregar 1 lo convierte de índice de matriz a fecha legible por humanos.
Roderick Obrist
136

La Dateclase JavaScript se encarga de esto por ti

var d = new Date("2012-02-29")
console.log(d)
// Wed Feb 29 2012 11:00:00 GMT+1100 (EST)

d.setDate(d.getDate() + 1)
console.log(d)
// Thu Mar 01 2012 11:00:00 GMT+1100 (EST)

console.log(d.getDate())
// 1
Phil
fuente
¿Seguirá funcionando si hoy fuera el último día de un mes, como el 31? Si agrega +1, ¿no terminaría en el puesto 32?
Timo
19
@Timo bastante seguro de que mi ejemplo demuestra exactamente eso
Phil
1
Oh, sí, tienes razón. Olvidé que febrero solo tiene 28 días :-)
Timo
Esto me falló hoy porque la nueva fecha ('2016-10-31') devuelve 'Dom 30 de octubre de 2016 23:00:00 GMT-0100 (AZOT)'. Estoy en las islas Azores y la zona horaria se cambió de AZOST a AZOT
nunoarruda
@nunoarruda lo siento, no estoy muy seguro de lo que está diciendo allí o qué tiene que ver con esta respuesta
Phil
7

Usaría la biblioteca DateJS. Puede hacer exactamente eso.

http://www.datejs.com/

Haga lo siguiente:

var d = new Date.today().addDays(1).toString("dd-mm-yyyy");

Date.today() - te da hoy a medianoche.

MattW
fuente
1
Me gusta más la respuesta de Phil ... Uso DateJS para todas las fechas, ¡pero parece que se puede hacer usando JS solo!
MattW
4
Date.parse ('mañana'). ToString ('dd-MM-aaaa');
geoffrey.mcgill
5

El método Date.prototype.setDate () acepta incluso argumentos fuera del rango estándar y cambia la fecha en consecuencia.

function getTomorrow() {
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1); // even 32 is acceptable
    return `${tomorrow.getFullYear()}/${tomorrow.getMonth() + 1}/${tomorrow.getDate()}`;
}
czerny
fuente
4

A continuación se utiliza una combinación de las respuestas de Roderick y Phil con dos condicionales adicionales que representan meses / días de un solo dígito.

Muchas API con las que he trabajado son exigentes con esto y requieren que las fechas tengan ocho dígitos (por ejemplo, '02022017'), en lugar de los 6 o 7 dígitos que la clase de fecha le dará en algunas situaciones.

function nextDayDate() {
      // get today's date then add one
      var nextDay = new Date();
      nextDay.setDate(nextDay.getDate() + 1);

      var month = nextDay.getMonth() + 1;
      var day = nextDay.getDate();
      var year = nextDay.getFullYear();

      if (month < 10) { month = "0" + month } 
      if (day < 10) { day = "0" + day }

      return month + day + year;
}
DNestoff
fuente
3

Casos de uso:

Date.tomorrow() // 1 day next 
Date.daysNext(1) // alternative Date.tomorrow()
Date.daysNext(2) // 2 days next. 

SI "mañana" no depende de hoy sino de otra fecha diferente de Date.now(), no use métodos estáticos sino que debe usar no estáticos:

es decir: viernes 05 de diciembre de 2008

 var dec5_2008=new Date(Date.parse('2008/12/05'));
 dec5_2008.tomorrow(); // 2008/12/06
    dec5_2008.tomorrow().day // 6
    dec5_2008.tomorrow().month // 12
    dec5_2008.tomorrow().year //2008
 dec5_2008.daysNext(1); // the same as previous
 dec5_2008.daysNext(7) // next week :)

API:

Dateold=Date;function Date(e){var t=null;if(e){t=new Dateold(e)}else{t=new Dateold}t.day=t.getDate();t.month=t.getMonth()+1;t.year=t.getFullYear();return t}Date.prototype.daysNext=function(e){if(!e){e=0}return new Date(this.getTime()+24*60*60*1e3*e)};Date.prototype.daysAgo=function(e){if(!e){e=0}return Date.daysNext(-1*e)};Date.prototype.tomorrow=function(){return this.daysNext(1)};Date.prototype.yesterday=function(){return this.daysAgo(1)};Date.tomorrow=function(){return Date.daysNext(1)};Date.yesterday=function(){return Date.daysAgo(1)};Date.daysNext=function(e){if(!e){e=0}return new Date((new Date).getTime()+24*60*60*1e3*e)};Date.daysAgo=function(e){if(!e){e=0}return Date.daysNext(-1*e)}
Abdennour TOUMI
fuente
3

Método 1: si no tiene problemas para usar otra biblioteca, entonces esto podría funcionar para usted usando moment.js

moment().add('days', 1).format('L');

Método 2: usando Date.js,

<script type="text/javascript" src="date.js"></script>    
var tomorrow = new Date.today().addDays(1).toString("dd-mm-yyyy"); 

Este método utiliza una biblioteca externa y no la biblioteca Date nativa. Como mi bootstrap-datetimepicker estaba usando moment.js y la biblioteca de fecha nativa, preferí el método 1. Esta pregunta menciona estos y algunos otros métodos.

Shiwangi
fuente
2

Es realmente simple:

1: Crea un objeto de fecha con la fecha y hora de hoy. 2: Use métodos de objeto de fecha para recuperar el día, mes y año completo y concatenarlos usando el operador +.

Visite http://www.thesstech.com/javascript/date-time JavaScript para obtener un tutorial detallado sobre la fecha y la hora.

Código de muestra:

  var my_date = new Date();  
  var tomorrow_date =       (my_date .getDate()+1)  + "-" + (my_date .getMonth()+1) + "-" + my_date .getFullYear();
  document.write(tomorrow_date);
Sohail Arif
fuente
Esto no se transfiere de fecha a mes, como ya observó el OP.
Wolfgang Kuehn
0
function getMonday(d)
{
   // var day = d.getDay();
   var day = @Config.WeekStartOn
   diff = d.getDate() - day + (day == 0 ? -6 : 0);
   return new Date(d.setDate(diff));
}
preetika
fuente
0

Lo mismo que la respuesta original, pero en una línea:

var tomorrow = new Date(Date.now() + 24 * 60 * 60 * 1000)

Los números representan 24 horas 60 minutos 60 segundos 1000 milisegundos.

Velter
fuente
1
Esta respuesta no es correcta ya que no se tiene en cuenta el horario de verano.
Decepcionado el
0

puedes probar esto:

function Tomorrow(date=false) {
    var givendate = (date!=false) ? new Date(date) : new Date();
    givendate.setDate(givendate.getDate() + 1);
    var day = givendate.getUTCDate()
    var month = givendate.getUTCMonth()+1
    var year = givendate.getUTCFullYear()
    result ="<b>" + day + "/" + month + "/" + year + "</b>";
    return result;
} 
var day = Tomorrow('2020-06-30');
console.log('tomorrows1: '+Tomorrow('2020-06-30'));
console.log('tomorrows2: '+Tomorrow());

Walter Nuñez
fuente
0
        Date.prototype.NextDay = function (e) {
        return new Date(this.getFullYear(), this.getMonth(), this.getDate() + ("string" == typeof e ? parseInt(e, 10) : e));
    }

    // tomorrow
    console.log(new Date().NextDay(1))

    // day after tomorrow
    console.log(new Date().NextDay(2))
Fhulufhelo Mokhomi
fuente
0

Usando JS solo (Pure js)

Hoy

new Date()
//Tue Oct 06 2020 12:34:29 GMT+0530 (India Standard Time)
new Date(new Date().setHours(0, 0, 0, 0))
//Tue Oct 06 2020 00:00:00 GMT+0530 (India Standard Time)
new Date(new Date().setHours(0, 0, 0,0)).toLocaleDateString('fr-CA')
//"2020-10-06"

mañana

new Date(+new Date() + 86400000);
//Wed Oct 07 2020 12:44:02 GMT+0530 (India Standard Time)
new Date(+new Date().setHours(0, 0, 0, 0) + 86400000);
//Wed Oct 07 2020 00:00:00 GMT+0530 (India Standard Time)
new Date(+new Date().setHours(0, 0, 0,0)+ 86400000).toLocaleDateString('fr-CA')
//"2020-10-07"
//don't forget the '+' before new Date()

Pasado mañana

Simplemente multiplique por dos ex: - 2 * 86400000

Puede encontrar todos los códigos cortos de configuración regional en https://stackoverflow.com/a/3191729/7877099

Isuru Dilshan
fuente
-1
        //-----------Date Configuration march 18,2014----------------------

        //alert(DateFilter);

        var date = new Date();
        y = date.getFullYear(), m = date.getMonth();
        var EndDate = new Date();



        switch (DateFilter) {
            case 'today': var StartDate = EndDate;   //todays date                 
                break;
            case 'yesterday':
                var d = new Date();
                var previousDate = new Date(d.getTime() - 1000 * 60 * 60 * 24);
                var StartDate = new Date(previousDate.yyyymmdd()); //yesterday Date
                break;
            case 'tomorrow':
                var d = new Date();
                var NextDate = new Date(d.getTime() + 1000 * 60 * 60 * 24);
                var StartDate = new Date(NextDate.yyyymmdd()); //tomorrow Date
                break;
            case 'thisweek': var StartDate = getMonday(new Date()); //1st date of this week
                break;
            case 'thismonth': var StartDate = new Date(y, m, 1);  //1st date of this month
                break;
            case 'thisyear': var StartDate = new Date("01/01/" + date.getFullYear());  //1st date of this year
                break;
            case 'custom': //var StartDate = $("#txtFromDate").val();                   
                break;
            default:
                var d = new Date();
                var StartDate = new Date(d.getTime() - 30 * 24 * 60 * 60 * 1000); //one month ago date from now.
        }


        if (DateFilter != "custom") {
            var SDate = $.datepicker.formatDate('@Config.DateFormat', StartDate); $("#txtFromDate").val(SDate);
            var EDate = $.datepicker.formatDate('@Config.DateFormat', EndDate); $("#txtToDate").val(EDate);
        }
        //-----------Date Configuration march 18,2014----------------------
preetika
fuente
Considere agregar una explicación a su respuesta.
Amar
-1
var curDate = new Date().toLocaleString().split(',')[0];

¡Simplemente! en formato dd.mm.aaaa.

Idan
fuente