2012-02-14 9 views
5

Quello che sto facendo è un sito web di previsioni del tempo, e quello di cui ho bisogno sono i giorni della settimana (ad esempio "Domenica", "Lunedi", ecc.). Per ottenere la data di domani sto solo mettendo "+ 1" come suggerito da qualcuno in un'altra domanda, ma quando arriva a sabato, dice "indefinito". Come faccio a renderlo così quando arriverà a sabato, + 1 passerà alla domenica? Grazie in anticipo!Ottieni la data di domani con getDay Javascript

var day=new Date(); 
var weekday=new Array(7); 
weekday[0]="Sunday"; 
weekday[1]="Monday"; 
weekday[2]="Tuesday"; 
weekday[3]="Wednesday"; 
weekday[4]="Thursday"; 
weekday[5]="Friday"; 
weekday[6]="Saturday"; 

document.getElementById('tomorrow').innerHTML = weekday[day.getDay() + 1]; 
document.getElementById('twodays').innerHTML = weekday[day.getDay() + 2]; 
document.getElementById('threedays').innerHTML = weekday[day.getDay() + 3]; 

risposta

7

Utilizzare (day.getDay() + i) % 7. Ciò restituirà solo risultati tra 0-6.

+0

Grazie tanto fayerth! Non so di cosa stia parlando andyortlieb: P –

+0

Scusa se stavo cercando di essere intelligente. Il codice è corretto, ma per fortuna solo la spiegazione è off-by-one;) 0-6. – andyortlieb

+0

@andyortlieb Grazie per la cattura. L'ho visto e l'ho risolto. :) – fayerth

26

Per aggiungere un giorno per un oggetto Date javascript si dovrebbe fare:

var date =new Date(); 
//use the constructor to create by milliseconds 
var tomorrow = new Date(date.getTime() + 24 * 60 * 60 * 1000); 

Nota, ottenere Data.

Date.getDay restituisce un numero da 0 a 6 in base al giorno della settimana.

Così si farebbe:

var date =new Date(); 
var tomorrow = new Date(date.getTime() + 24 * 60 * 60 * 1000); 
var twoDays = new Date(date.getTime() + 2 * 24 * 60 * 60 * 1000); 
var threeDays = new Date(date.getTime() + 3 * 24 * 60 * 60 * 1000); 

document.getElementById('tomorrow').innerHTML = weekday[tomorrow.getDay()]; 
document.getElementById('twodays').innerHTML = weekday[twoDays.getDay()]; 
document.getElementById('threedays').innerHTML = weekday[threeDays.getDay()]; 

Modifica: errore di battitura di fissaggio

+0

Grazie, ma non è quello che cercavo. Fayerth ha risposto alla mia domanda, grazie. –

+1

@JordanClark Ho aggiornato la mia risposta. – gideon

Problemi correlati