Javascript convert date and time today and save .txt file using its format

Target: When download linked is clicked, a .text will be automatically downloaded named the date and time format for today. (eg: 7-3-2021 04:04:00 PM or which ever format is applicable as long as the date and time is on the name)

This is the code for the link:

<a download="info.txt" id="downloadlink" style="display: none"><button class="btn btn-block btn-warning">Download</button></a>

While here is the code for the function:

(function () {
        var textFile = null,
          makeTextFile = function (text) {
            text = text.replace(/n/g, "rn");
            var data = new Blob([text], {type: 'text/plain'});

            // If we are replacing a previously generated file we need to
            // manually revoke the object URL to avoid memory leaks.
            if (textFile !== null) {
              window.URL.revokeObjectURL(textFile);
            }

            textFile = window.URL.createObjectURL(data);

            return textFile;
          };

          var create = document.getElementById('create'),
            textbox = document.getElementById('todayGeneratedReport');

          create.addEventListener('click', function () {
            var link = document.getElementById('downloadlink');
            link.href = makeTextFile(textbox.value);
            link.style.display = 'block';
          }, false);
        })();

The code is good but I’m having issues on how to make it happen. Currently, when download link is clicked, a info.text file is being saved but my target is to saved it using the date and time format when the link is clicked.

Do I need to create another function and import it to the download property of the link? Please help. Thanks.

Answer

Besides modifying link href and style, you can modify its download attribute as well. Here’s one way to do it:

create.addEventListener('click', function () {
  var filename = new Date().toLocaleString('en-US') + '.txt';
   
  var link = document.getElementById('downloadlink');
  link.href = makeTextFile(textbox.value);
  link.setAttribute('download', filename);
  link.style.display = 'block';
}, false);