2012-02-25 10 views
58

Io sto cercando di ottenere il supporto JavaScript per visualizzare la data domani in formato (gg-mm-aaaa)JavaScript come ottenere data di domani nel formato gg-mm-aa

Io ho questo script, che visualizza data odierna in 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) 

Ma come faccio a farlo domani per visualizzare la data nello stesso formato cioè 26/2/2012

ho provato questo:

var day = currentDate.getDate() + 1 

Tuttavia ho potuto mantenere +1 e andare oltre il 31, ovviamente, non ci sono> 32 giorni in un mese

cercato per ore, ma sembra essere una risposta o una soluzione intorno a questo?

risposta

123

Questo dovrebbe risolvere il problema molto bene di te.

Se passate il costruttore di Date per un tempo, 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 restituisce la data di esattamente 24 ore da oggi, che può essere impreciso intorno l'ora legale.

in qualsiasi momento il proprio lavoro la risposta di Phil:

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

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

+7

Grazie bro, avere una buona vita –

+6

Grazie, un po 'più corto 'var DataCorrente = new Date (+ new Date() + 86400000);' – Ikrom

+8

Si noti che con questa strategia è possibile eseguire in problemi relativi all'ora legale, che fa sì che un giorno dell'anno abbia 23 ore e uno ne abbia 25.La risposta di Phil sotto evita questo problema. – gsf

102

La JavaScript Date classe gestisce questo per voi

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

Funzionerà ancora se oggi fosse l'ultimo giorno di un mese, come il 31? Se aggiungi +1 non arriverai alla 32esima? – Timo

+13

@Timo abbastanza sicuro che il mio esempio dimostra esattamente che – Phil

+1

Oh, sì hai ragione. Ho dimenticato quel febbraio ha solo 28 giorni :-) – Timo

5

Vorrei utilizzare la libreria DateJS. Può fare esattamente questo.

http://www.datejs.com/

La effettuare le seguenti operazioni:

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

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

+1

Mi piace la risposta di Phil meglio ... Uso DateJS per tutte le date, ma sembra che si possa fare usando solo JS! – MattW

+0

[moment.js] (http://momentjs.com/) può anche aiutare con questo. – rodneyrehm

+4

Date.parse ('tomorrow'). ToString ('dd-MM-yyyy'); –

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

Per favore considera l'aggiunta di una spiegazione alla tua risposta. – Amar

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

I casi d'uso:

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

SE "domani" non è dipende di oggi, ma di un altro data diversa di Date.now(), non utilizzare metodi statici, ma piuttosto è necessario utilizzare non statico:

i.e: Fri Dec 05 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)} 
2

Metodo Date.prototype.setDate() accetta anche argomenti al di fuori della gamma standard e cambia 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()}`; 
} 
1

sua davvero semplice:

1: Creare oggetto Date con la data e l'ora di oggi'. 2: utilizzare i metodi degli oggetti data per recuperare giorno, mese e anno intero e concatenarli utilizzando l'operatore +.

Visita http://www.thesstech.com/javascript/date-time JavaScript per tutorial dettagliato su data e ora.

codice di esempio:

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

Metodo 1: se non si dispone di problemi nell'uso di altra libreria, allora questo potrebbe funzionare per voi utilizzando moment.js

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

Metodo 2: Utilizzo di Data. 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 di date nativa. Come il mio bootstrap-datetimepicker era utilizzando moment.js e la biblioteca della data originaria, ho preferito il metodo 1. La presente question menzioni questi ed alcuni altri metodi.

2

Il sotto utilizza una combinazione di Roderick e risposte di Phil con due condizionali extra che rappresentano una cifra mesi/giorni.

molte API con cui ho lavorato sono pignoli su questo, e richiedono le date per avere otto cifre (ad esempio '02.022.017'), invece dei 6 o 7 cifre classe data sta per dare 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; 
} 
Problemi correlati