-1

var today = new Date()
var time = today.getFullYear() +'-'+ today.getMonth()+1 +'-'+ today.getDate();
document.getElementById("date").innerHTML = time;
<p1 id = "date" />

I've used this code for another task on this same HTML page and it worked

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71

2 Answers2

2

You have error in your syntax. Remove the ' at the end of your js. Also you can use today.toISOString() to format the date as 'Y-m-d'.

var today = new Date();
document.getElementById("date").innerHTML = today.toISOString();

Also, p1 doeas not exist. You surely mean <p> or in your code: <p id="date"></p>

Atomkind
  • 341
  • 2
  • 11
  • Thanks. So i previously used the p tag for a getElementbyID previously. That's why I created a p1. I thought the p tag could be increased by p1, p2 etc. So that they can be manipulated or styled individually. Sorry if what I'm saying doesn't make sense. – user15286356 Feb 25 '21 at 22:41
  • So, since I've used the p tag already and used its ID. How do I manipulate this new command then? – user15286356 Feb 25 '21 at 22:42
  • The apostrophe you mentioned was erroneoulsy put when I copy-pasted here. It's not on my real doc but the issue still remains. – user15286356 Feb 25 '21 at 22:44
  • the p tag you can use as often as you want, just headline tags are h1, h2, h3, h4, h5 and h6. Any ID has to be individal like `

    `. What is the exact error and from where do you get it? Console? Browser? Errorlog?
    – Atomkind Feb 25 '21 at 22:49
  • The error is from the console and the date doesn't pop-up as output. I'm just trying my hands at different things because I'm new to js. – user15286356 Feb 26 '21 at 00:50
0

This code works for me.

<html><head></head>
<body>
<p1 id = "date" />
<script>
var today = new Date();
var time = today.getFullYear() + "-"+ today.getMonth()+1+ today.getDate();
document.getElementById("date").innerHTML = time;
</script>
</body></html>

The p1 tag needs to exist before the script block is called, or the "date" element will be null.

Here is some code that can help with debugging.

<html><body>
<p id = "date1" />
<script>
var el_1 = document.getElementById("date1");
var el_2 = document.getElementById("date2");
alert("el_1=" + el_1  + "\n" + "el_2=" + el_2);
</script>
<p id="date2" />
</body></html>

When I run the second code, I get el_2=null.

gary
  • 26
  • 3