Trouble getting the date | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Trouble getting the date

So I'm trying to make a program to display something specific depending on which day of the week it is but I'm struggling with getting the program to get which day of the week it is. here is what I have so far https://code.sololearn.com/W335n1j2LkS1/#javascript

27th Apr 2017, 4:56 PM
Zac Parnell
Zac Parnell - avatar
8 Answers
+ 3
If you want to get Monday...Sunday , you should write like this var today = new Date(); var weekday = [ "Sunday", "Monday","Tuesday", "Wednesday","Thursday","Friday","Saturday"]; console.log(weekday[today.getDay()]);
27th Apr 2017, 5:04 PM
黃冠融
黃冠融 - avatar
+ 7
// As already said, you need to append parenthesis to the function name for calling it: var today = new Date(); var dd = today.getDay(); // and you get a number from 0 to 6 representing the actual day in a week ( not the week ), so you don't have to test this: if (dd <10) { dd = '0'+dd; } today = dd; // as dd is always lighter than 10 ^^ // so, you can just output dd; document.write(dd);
27th Apr 2017, 5:11 PM
visph
visph - avatar
+ 7
To simplify, give an id to your "today is" container: <p id="date">Today is</p> And in your js: document.getElementById('date').innerHTML+=' '+today; Or define a container for the day name, and change it's innerHTML value as previously ( but without need to concatenate to the actual value with += ): <p>Today is <span id="date"></span></p> document.getElementById('date').innerHTML=' '+today;
27th Apr 2017, 5:30 PM
visph
visph - avatar
+ 5
That's probably because the JS is executing before the Html page is fullly loaded ( and DOM isn't ready ^^ ): in code playground, the JS tab is equivalent to a linked file in the <head> section... so, JS is executed before <body> content is parsed. You have to wait for its avainility: simplest way is to embed all the JS tab code in an anonymized function assigned to the window 'onload' event: window.onload = function() { // your JS code };
28th Apr 2017, 2:06 AM
visph
visph - avatar
+ 3
getday should have () because it is a function. And getDay will return week
27th Apr 2017, 4:58 PM
黃冠融
黃冠融 - avatar
+ 1
You can excute the code that I wrote here : https://code.sololearn.com/WDoV60l2y8Tt/?ref=app
27th Apr 2017, 5:09 PM
黃冠融
黃冠融 - avatar
+ 1
I have one last question, I now have it working, but I want to display the phrase from the JS on the same line as "Today is" from the HTML how can I do that?
27th Apr 2017, 5:22 PM
Zac Parnell
Zac Parnell - avatar
+ 1
@visph when I try this it gives me an error saying it can't set property of innerHTML to null am I typing something in wrong?
27th Apr 2017, 6:43 PM
Zac Parnell
Zac Parnell - avatar