Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get tomorrow's date with getDay Javascript

What I am making is a weather forecast website, and what I need is the days of the week (ie. "Sunday", "Monday", etc.). To get tomorrow's date I am just putting "+ 1" like someone suggested in another question, but when it get's to Saturday, it says "undefined". How do I make it so when it gets to Saturday, + 1 will loop over to Sunday? Thanks in advance!

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];
like image 609
Jordan Clark Avatar asked Feb 14 '12 04:02

Jordan Clark


People also ask

How can I get tomorrow date by moment?

let today = moment(); let tomorrow = moment(). add(1,'days'); let yesterday = moment(). add(-1, 'days');

How do you know if a date is tomorrow?

To check if a date is tomorrow's date:Add 1 day to the current date to get tomorrow's date.

How check if a form date is before today JavaScript?

How do you check if a date is before current date in JavaScript? const date = new Date('2022-09-24'); // 👇️ 1663977600000 console. log(date.To check if a date is before today's date: Use the Date() constructor to create a new date.

How do I get the next Sunday in JavaScript?

function getSundayOfCurrentWeek() { const today = new Date(); const first = today. getDate() - today. getDay() + 1; const last = first + 6; const sunday = new Date(today. setDate(last)); return sunday; } // (today is Mon Jan 17 2022) // 👇️ Sun Jan 23 2022 console.


2 Answers

To add a day to a javascript Date object you would do :

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

Note, getDate.

Date.getDay returns a number from 0-6 based on what day of the week it is.

So you would do:

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

Edit: Fixing typo

like image 147
gideon Avatar answered Oct 21 '22 03:10

gideon


Use (day.getDay() + i) % 7. That will only return results between 0-6.

like image 41
seeming.amusing Avatar answered Oct 21 '22 04:10

seeming.amusing