0

year is not defined (JS)

function printTime() { var d = new Date(); var year = d.getFullYear(); var month = d.getMonth(); var day = d.getDate(); var hours = d.getHours(); var mins = d.getMinutes(); var secs = d.getSeconds(); var msecs = d.getMilliseconds(); if (month == 0) { return January} else if (month == 1){ return February} else if (month == 2){ return March} else{ return April} } document.body.innerHTML = year+"/"+month+"/"+day+"<br/>"+hours+":"+mins+":"+secs+":"+msecs; setInterval(printTime, 1); please help me what's wrong here...

18th Apr 2018, 7:52 AM
Simonas VaĆĄkys
Simonas VaĆĄkys - avatar
7 Answers
+ 1
Create a new file, call it test.htm and just paste in this code: <html> <head> </head> <body> <script> function printTime() { var d = new Date(); var year = d.getFullYear(); var month = d.getMonth(); var day = d.getDate(); var hours = d.getHours(); var mins = d.getMinutes(); var secs = d.getSeconds(); var msecs = d.getMilliseconds(); var monthsArr = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; document.body.innerHTML = year+"/"+monthsArr[month]+"/"+day+"<br/>"+hours+":"+mins+":"+secs+":"+msecs; } setInterval(printTime, 1000); </script> </body> </html> Save and open it in browser. If you'll need more explaining about something please ask :)
18th Apr 2018, 10:50 AM
Luigi
Luigi - avatar
+ 6
https://code.sololearn.com/W2zqv2zPPA32/?ref=app The month names being returned should be a String as it is returning some kind of object ( I believe) and I added a p tag to display the output. I also moved it all to the script tag and saw that it worked that way.
18th Apr 2018, 8:02 AM
Tarantino
Tarantino - avatar
+ 1
Thank you, guys đŸ€—
18th Apr 2018, 10:35 AM
Simonas VaĆĄkys
Simonas VaĆĄkys - avatar
0
But why u write this whole code in html but not in JS? And i want that month will be displayed as April not 3
18th Apr 2018, 8:09 AM
Simonas VaĆĄkys
Simonas VaĆĄkys - avatar
0
Here's a simple implementation of the concept. Hint: return statement inside a function will stop the function itself and output (or return) a value to the caller, so use it until you know that that particular function must return a value. function printTime() { var d = new Date(); var year = d.getFullYear(); var month = d.getMonth(); var day = d.getDate(); var hours = d.getHours(); var mins = d.getMinutes(); var secs = d.getSeconds(); var msecs = d.getMilliseconds(); var monthsArr = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; document.body.innerHTML = year+"/"+monthsArr[month]+"/"+day+"<br/>"+hours+":"+mins+":"+secs+":"+msecs; } setInterval(printTime, 1000);
18th Apr 2018, 8:22 AM
Luigi
Luigi - avatar
0
No problem! 👍
18th Apr 2018, 10:41 AM
Luigi
Luigi - avatar
- 1
umm, i've tried this, but year is still not defined..
18th Apr 2018, 10:45 AM
Simonas VaĆĄkys
Simonas VaĆĄkys - avatar