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
8 Antworten
+ 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()]);
+ 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);
+ 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;
+ 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
};
+ 3
getday should have () because it is a function.
And getDay will return week
+ 1
You can excute the code that I wrote here :
https://code.sololearn.com/WDoV60l2y8Tt/?ref=app
+ 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?
+ 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?