Home > Blockchain >  Copy Date to Clipboard onclick
Copy Date to Clipboard onclick

Time:01-26

I might be making things overly complicated :p But I can't get it to work.

I'm trying to copy "todays date" to the clipboard

<a href="javascript:copydateToClipboard()">Date</a>
<script> 
function copydateToClipboard() {
Date.prototype.toShortFormat = function() {
    const monthNames = ["January", "February", "March", "April",
                        "May", "Juni", "July", "August",
                        "September", "October", "November", "December"];
    const day = this.getDate()-1;
    const monthIndex = this.getMonth();
    const monthName = monthNames[monthIndex];
    const year = this.getFullYear();
    return `${year}_${monthName}_${day}`;  }
let anyDate = new Date(1528578000000);
console.log(anyDate.toShortFormat());
let today = new Date();
//copydate to clipboard
  const str = "${today}"
  const el = document.createElement('textarea')
  el.value = str
  el.setAttribute('readonly', '')
  el.style.position = 'absolute'
  el.style.left = '-9999px'
  document.body.appendChild(el)
  el.select()
  document.execCommand('copy')
  document.body.removeChild(el)
}
</script>    

Taken from an url reform script.

CodePudding user response:

Got it:

<a href="javascript:copydateToClipboard()">Date</a>
<script> 
function copydateToClipboard() {
  var nowd = new Date().toUTCString().slice(0,16);
  //const str = "${nowd}"
  const el = document.createElement('textarea')
  el.value = nowd
  el.setAttribute('readonly', '')
  el.style.position = 'absolute'
  el.style.left = '-9999px'
  document.body.appendChild(el)
  el.select()
  document.execCommand('copy')
  document.body.removeChild(el)
}
</script>
  • Related