Using JavaScript, capture the current date and time and store it in a .txt file with the corresponding format

Objective: Upon clicking the download link, an automatically named file will be downloaded with today's date and time format. For example, 7-3-2021 04:04:00 PM or any applicable format with the date and time included in the name.

Below is the code snippet for the download link:

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

And here is the code for the function:

(function () {
        var textFile = null,
          makeTextFile = function (text) {
            text = text.replace(/\n/g, "\r\n");
            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);
        })();

Although the code is correct, I am facing issues with implementing the date and time format for the downloaded file. Currently, the file is saved as info.txt when the link is clicked. Is it necessary to create a new function and link it to the download property of the link? Any assistance on this matter would be greatly appreciated. Thank you.

Answer №1

In addition to changing the link's href and style, you have the option to modify its download attribute as well. Check out this method:

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);

Answer №2

HTML5 introduces the a[download] attribute, allowing you to rename downloaded files. For example, you can download link.txt and rename it as today.txt.

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

If you want the file to be named with today's date, simply include it in the download attribute.

To achieve this dynamically, make a slight modification to your code.

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

You can customize the formatDate function as needed:

const formatDate = (date)=>date.now();

Answer №3

Thank you to everyone who provided suggestions. Your input was instrumental in helping me resolve the issue.

Here's what I did:

var fileUpdated = new Date().toLocaleString();

            Date.prototype.yyyymmdd = function() {
              var yyyy = this.getFullYear();
              var mm = this.getMonth() < 9 ? "0" + (this.getMonth() + 1) : (this.getMonth() + 1); // getMonth() is zero-based
              var dd = this.getDate() < 10 ? "0" + this.getDate() : this.getDate();
              return "".concat(yyyy + "-").concat(mm + "-").concat(dd + "-");
            };

            Date.prototype.yyyymmddhhmm = function() {
              var yyyymmdd = this.yyyymmdd();
              var hh = this.getHours() < 10 ? "0" + this.getHours() : this.getHours();
              var min = this.getMinutes() < 10 ? "0" + this.getMinutes() : this.getMinutes();
              return "".concat(yyyymmdd).concat(hh + "-").concat(min + "-");
            };

            Date.prototype.yyyymmddhhmmss = function() {
              var yyyymmddhhmm = this.yyyymmddhhmm();
              var ss = this.getSeconds() < 10 ? "0" + this.getSeconds() : this.getSeconds();
              return "".concat(yyyymmddhhmm).concat(ss);
            };

            var d = new Date();

            var fileUpdated = d.yyyymmddhhmmss();

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

I implemented o-o's solution as recommended due to the time format variations in different countries. It's now functioning correctly :-)

Thank you for your assistance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Picture in the form of a radio button

Is there a way to use an image instead of a radio button in my AngularJS form? I have managed to hide the radio button using CSS, but it disables the checked event. How can I make the image clickable? position: absolute; left: -9999px; Here is the code s ...

if else statement fails to work in ajax-based login form

I tried to create the code below by referencing processes.php, submit form, and ajax from various sources on the internet. However, my code doesn't seem to be working properly. proccess.php <?php session_start(); ini_set('display_errors&apos ...

Tips for effectively utilizing the useDraggable and useSortable hooks within the dnd-kit library

I'm currently working on developing a basic calculator using React and dnd-kit. The idea is to have draggable elements in the calculator that can be sorted within a droppable area with smooth animation effects. However, I've encountered an issue ...

Create objects in the gallery

I recently developed a React Material-UI component using Typescript: <Grid container direction="row" justifyContent="flex-start" alignItems="flex-start"> <Grid item xs={5}> <B ...

Choosing multiple options from a list

I am working on a messaging app where users can compose and send messages to contacts. Currently, I am only able to send messages to one contact at a time. My goal is to enable users to select multiple contacts to create group messages. Since I am new to a ...

Passing multiple functions to child components in ReactJS as a single prop

I am utilizing the technique of passing multiple functions as individual props from the parent component to its child components. Everything is working correctly without any errors or problems, but I'm interested in exploring if there is a more effici ...

Concealing Website Elements with javascript based on class assignments

Despite my hesitation, I have to ask this question after unsuccessful searches in related articles. In my code, I have 7 nav links all with the same class. Due to the length of the HTML, I am looking for a way to hide contents until the link is clicked, an ...

NodeJs Importing a File

Currently working with NodeJS, I have encountered a challenge. Is it possible to require a JavaScript file in Node similar to how we do in browsers? When using the require() method, I noticed that the JavaScript file called does not have access to global v ...

Tips for restricting text within a div container

Currently, on my to-do list website, I am facing an issue with displaying long event titles in a div on the home screen. The text overflows, and even though I have set the x-overflow to hidden, it's not providing the desired result. I have tried using ...

Using Chart.js to display JSON data in a graphical format

I am facing an issue and need some help. I have gone through various tutorials and questions, but none of them seem to address my specific problem. When making an ajax request to my PHP file, I receive a JSON response like this (as seen in the console log) ...

Using jQuery, include a variable within an anchor tag

Struggling to insert a variable into a jQuery link, but my attempts have all failed. Check out this example: let url = "www.google.com?s=" + id; $("#test").append("<a href='" + url + "'>Test</a>"); ...

Create interactive highcharts graphs using data from a CSV file generated through PHP

I'm having trouble working with Highcharts and csv data. Take a look at this example: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/line-ajax/ $.getJSON('http://www.highcharts.com/ ...

Angular.js and DAO design pattern

Admitting my newness to Angular.js and lack of experience with frameworks like Backbone or Knockout, I am venturing into building an application that interacts with a server using a RESTful API. After delving deep into the angular documentation and blog po ...

The Three JS on the website is error-free, yet it fails to function properly

I've been attempting to replicate the example three.js page on my own website, complete with a canvas for the 3D animation. However, I'm encountering an issue where nothing is displayed, despite no errors appearing. I've tried troubleshootin ...

Tips on incorporating several class names into Next.js elements

My current challenge involves an unordered list element with the following structure: <ul className={styles["projects-pd-subdetails-list"]}> {detail.subdetails.map((sub) => ( <li className={styles[ ...

Node.js/Express - unable to retrieve client body data on server

I am able to retrieve data from express but I am facing issues when trying to post data to express... client: <html> <button onclick="myFunction()">send</button> <script> const data = {"experience" : 0}; ...

Developing an npm library with ReactJs: A step-by-step guide

As a newcomer to React, I am eager to create my own npm library in ReactJS. Taking inspiration from my existing React project, the goal is to transform it into a package (or library) that can be easily integrated into other projects. This means allowing ...

Troubleshooting jQuery Dropdown Menu Animation Bugs

Take a look at this interesting fiddle: https://jsfiddle.net/willbeeler/tfm8ohmw/ HTML: <a href="#" class="roll-btn">Press me! Roll me down and up again!</a> <ul class="roll-btns"> <li><a href="#" class="control animated noshow ...

What is causing the issue with Vue.js :class not functioning properly when it relies on a property of a list

Here is a snippet of my HTML code: <tr v-for="product in products" :class="{'bg-red': product.toWrite }" :key="product.name"> <td @click="setObjectToWrite(product.name)" class="show-hover&qu ...

Problem Encountered with Bootstrap 3 Date and Time Selector

I am currently utilizing the date/time picker created by Eonasdan, which can be accessed here. Below is the HTML code snippet from the example: <div class="container"> <div class="col-md-10"> <div class='well'> ...