-2

Displaying only today's date unable to get time.

<script type="text/javascript">
n =  new Date();
y = n.getFullYear();
m = n.getMonth() + 1;
d = n.getDate();
document.getElementById("date").innerHTML = m + "/" + d + "/" + y;
</script>

<li id="date"></li>
  • 1
    Why not read this https://learn.microsoft.com/en-us/scripting/javascript/reference/date-object-javascript? – Ed Heal Dec 22 '17 at 12:44
  • @JJJ I need to display as well how the date is displaying in the same format time should be displayed – user9131066 Dec 22 '17 at 12:49
  • 1
    I have no idea what that means, or what your actual problem is. Show an example of what you want to see. – JJJ Dec 22 '17 at 12:50
  • @JJJ need to display present date and time – user9131066 Dec 22 '17 at 12:51
  • 1
    Have you read any [documentation for `Date`](https://learn.microsoft.com/en-us/scripting/javascript/reference/date-object-javascript) that would show what methods to use to get minutes and hours? Have you Googled for "show current time in javascript"? – JJJ Dec 22 '17 at 12:55

2 Answers2

0

You need to add the code to extract hours, minutes and seconds and then append them to the string. See below.

n =  new Date();
y = n.getFullYear();
m = n.getMonth() + 1;
d = n.getDate();
hour = n.getHours();
min = n.getMinutes();
sec = n.getSeconds();
document.getElementById("date").innerHTML = m + "/" + d + "/" + y + ' ' + hour + ':' + min + ':' + sec ;
<li id="date"></li>
Ed Heal
  • 59,252
  • 17
  • 87
  • 127
-2

Your code is perfekt, but you didn't checked the runtime problems.

If you run your js code after declaring of the div it works. Because, the javascript search after a id that not exits on the dom. If you change the sort of code the runtime problem will be removed. Plunker Example

<li id="date"></li>    
<script type="text/javascript">
n =  new Date();
y = n.getFullYear();
m = n.getMonth() + 1;
d = n.getDate();
document.getElementById("date").innerHTML = m + "/" + d + "/" + y;
</script>

Problem Solution 2

If you want you can use moment libery of date/time it very useful. Moment JS Libary

Gerlando Caldara
  • 313
  • 1
  • 3
  • 10