How can one fetch and print the current year without using document.write()
in JavaScript?
This is for a typical copyright line in the footer; e.g., © 2017 Stack Overflow.
Right now I’m using the standard document.write()
method.
JavaScript
x
2
1
document.write(new Date().getFullYear());
2
Advertisement
Answer
Yes sure you can use an element:
JavaScript
1
2
1
<p>© Stack Overflow <span id="year"> </span></p>
2
Add a link to your JS like so:
JavaScript
1
2
1
<script src="js/app.js"></script>
2
And within this file you can do:
JavaScript
1
4
1
var date = new Date().getFullYear();
2
3
document.getElementById("year").innerHTML = date;
4
Alternatively you can simply use php like so:
JavaScript
1
2
1
<?php echo date("Y"); ?>
2
If you are using php just make sure you change the file ext to PHP.