<html>
<div id="current_date"></p>
<script>
date = new Date();
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
document.getElementById("current_date").inn
erHTML = year + "-" + day+ "-" + month;
</script>
<button>Copy Date</button>
</html>
Asked
Active
Viewed 37 times
-4

Progman
- 16,827
- 6
- 33
- 48
1 Answers
0
Welcome to StackOverflow. Please read this for the future as your future questions will probably be closed without answers otherwise: https://stackoverflow.com/help/how-to-ask
You've already figured out how to get the Date in the format you want, however, you want to use .value
and not .innerHTML
to get the text into the input. innerHTML is used for divs, spans and other elements while value applies to any element where its value can be defined (textbox, etc...).
document.getElementById("current_date").value = year + "-" + day+ "-" + month;
Once it's in the input you just need to select it. The setSelectionRange
is redundant on desktops but is useful for mobiles as not all of them accept .select()
. Then the last line copies the selection into the clipboard.
copyText.select();
copyText.setSelectionRange(0, 99999);
navigator.clipboard.writeText(copyText.value);
Here's the code:
date = new Date();
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
document.getElementById("current_date").value = year + "-" + day+ "-" + month;
var copyText = document.getElementById("current_date");
copyText.select();
copyText.setSelectionRange(0, 99999);
navigator.clipboard.writeText(copyText.value);

Ralph
- 337
- 4
- 13