JavaScript come ottenere la data di domani in formato gg-mm-aa


90

Sto cercando di ottenere JavaScript per visualizzare la data di domani in formato (gg-mm-aaaa)

Ho questo script che mostra la data odierna in formato (gg-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)

Ma come faccio a visualizzare la data di domani nello stesso formato, ad es 26/2/2012

Ho provato questo:

var day = currentDate.getDate() + 1

Tuttavia potrei mantenere +1e superare i 31 ovviamente non ci sono> 32 giorni in un mese

Stai cercando ore ma sembra non esserci una risposta o una soluzione a questo?

Risposte:


176

Questo dovrebbe risolverlo davvero bene per te.

Se passi un po 'di tempo al costruttore Date, farà il resto del lavoro.

24 ore 60 minuti 60 secondi 1000 millisecondi

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 da tenere a mente è che questo metodo restituirà la data esattamente 24 ore da adesso, il che può essere impreciso intorno all'ora legale.

La risposta di Phil funziona in qualsiasi momento:

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

Il motivo per cui ho modificato il mio post è perché io stesso ho creato un bug che è venuto alla luce durante l'ora legale utilizzando il mio vecchio metodo.


9
Grazie, un po 'più brevevar currentDate = new Date(+new Date() + 86400000);
Ikrom

13
Nota che con questa strategia potresti incorrere in problemi relativi all'ora legale, che fa sì che un giorno dell'anno abbia 23 ore e uno 25. La risposta di Phil di seguito evita questo problema.
gsf

3
new Date().getTime()può essere semplificato comeDate.now()
czerny

Sono entrambi corretti, non credo che IE8 abbia Date.now () però.
Roderick Obrist

2
@ConorB, .getMonth () restituisce 0 per gennaio, 1 per febbraio ... ecc. 11 per dicembre. L'aggiunta di 1 lo trasforma da indice di matrice a data leggibile dall'uomo.
Roderick Obrist

136

La Dateclasse JavaScript gestisce questo per te

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

Funzionerà ancora se oggi fosse l'ultimo giorno di un mese, come il 31? Se aggiungi +1 non finiresti con il 32 °?
Timo

19
@Timo sono abbastanza sicuro che il mio esempio lo dimostri esattamente
Phil

1
Oh, sì, hai ragione. Dimenticavo che febbraio ha solo 28 giorni :-)
Timo

Questo non è riuscito per me oggi perché la nuova data ('2016-10-31') restituisce 'Sun Oct 30 2016 23:00:00 GMT-0100 (AZOT)'. Sono nelle isole Azzorre e il fuso orario è stato cambiato da AZOST ad AZOT
nunoarruda

@nunoarruda scusa, non sono sicuro di cosa stai dicendo lì o cosa ha a che fare con questa risposta
Phil

7

Userei la libreria DateJS. Può fare esattamente questo.

http://www.datejs.com/

Fai quanto segue:

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

Date.today() - ti dà oggi a mezzanotte.


1
Mi piace di più la risposta di Phil ... Uso DateJS per tutte le date, ma sembra che possa essere fatto usando solo JS!
MattW

4
Date.parse ('domani'). ToString ('dd-MM-yyyy');
geoffrey.mcgill

5

Il metodo Date.prototype.setDate () accetta argomenti pari al di fuori dell'intervallo standard e modifica la data di conseguenza.

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

4

Di seguito viene utilizzata una combinazione delle risposte di Roderick e Phil con due condizionali extra che rappresentano mesi / giorni a una cifra.

Molte API con cui ho lavorato sono pignole su questo punto e richiedono che le date abbiano otto cifre (ad esempio "02022017"), invece delle 6 o 7 cifre che la classe della data ti fornirà in alcune situazioni.

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;
}

3

Casi d'uso :

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

SE "domani" non dipende da oggi ma da un'altra data diversa da Date.now(), non utilizzare metodi statici ma piuttosto non statici:

cioè: ven 5 dicembre 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)}

3

Metodo 1: se non hai problemi nell'usare un'altra libreria, allora questo potrebbe funzionare per te usando moment.js

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

Metodo 2: utilizzo di Date.js,

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

Questo metodo utilizza la libreria esterna e non la libreria Date nativa. Poiché il mio bootstrap-datetimepicker utilizzava moment.js e la libreria di date nativa, ho preferito il metodo 1. Questo domanda menziona questi e alcuni altri metodi.


2

È davvero semplice:

1: crea l'oggetto data con la data e l'ora odierne. 2: utilizzare i metodi dell'oggetto data per recuperare giorno, mese e anno completo e concatenarli utilizzando l'operatore +.

Visitare http://www.thesstech.com/javascript/date-time JavaScript per esercitazioni dettagliate su data e ora.

Codice d'esempio:

  var my_date = new Date();  
  var tomorrow_date =       (my_date .getDate()+1)  + "-" + (my_date .getMonth()+1) + "-" + my_date .getFullYear();
  document.write(tomorrow_date);

Ciò non viene trasferito dalla data al mese, come già osservato dal PO.
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));
}

0

La stessa della risposta originale, ma in una riga:

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

I numeri stanno per 24 ore 60 minuti 60 secondi 1000 millisecondi.


1
Questa risposta non è corretta perché l'ora legale non viene presa in considerazione.
Deluso il

0

puoi provare questo:

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());


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))

0

Usare solo JS (Pure js)

Oggi

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"

Domani

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()

Dopodomani

Basta moltiplicare per due ex: - 2 * 86400000

Puoi trovare tutti gli shortcode locali da https://stackoverflow.com/a/3191729/7877099


-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----------------------

Considera l'idea di aggiungere una spiegazione alla tua risposta.
Amar

-1
var curDate = new Date().toLocaleString().split(',')[0];

Semplicemente! in formato gg.mm.aaaa.

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.