4

In short

How can I make a file's name contain the user's local time upon downloading it?
Example:

<a href="/pizza.pdf" download="pizza-CURRENT-USER-TIME-HERE.pdf">Click here</a>

In long

What about the download having the user's time in the name?

With PHP, I know I can echo a variable into the file's name, like this:

PHP:

date_default_timezone_set('America/New_York');
$current_date = date('Y-F-j-h-i-s');

HTML:

<a href="/pizza.pdf" download="pizza-<?php echo $current_date; ?>.pdf">Click here</a>

Or, with JavaScript, I can print the user's local time in the link (or anywhere on the screen).

How can I get the user's local time as the value for the download attribute?

I'm open to using PHP, JS, JQuery, etc.

1 Answers1

19

You can do this most simply with the onclick attribute.

<a href="/pizza.pdf" download="pizza-CURRENT-USER-TIME-HERE.pdf" onclick="this.download='pizza-' + getFormattedTime() + '.pdf'">Click here</a>

Or, if you want to use Jquery:

In HTML (adding an id so we can select):

<a href="/pizza.pdf" download="pizza-CURRENT-USER-TIME-HERE.pdf" id="download">Click here</a>

In JS:

$("#download").click(function() {
    this.download= 'pizza-' + getFormattedTime() + '.pdf'
}

Now, when the user clicks the link, the download name will be changed immediately to the current time.

Here's an example for how to get the time (heavily based on this answer):

function getFormattedTime() {
    var today = new Date();
    var y = today.getFullYear();
    // JavaScript months are 0-based.
    var m = today.getMonth() + 1;
    var d = today.getDate();
    var h = today.getHours();
    var mi = today.getMinutes();
    var s = today.getSeconds();
    return y + "-" + m + "-" + d + "-" + h + "-" + mi + "-" + s;
}
Jesus is Lord
  • 14,971
  • 11
  • 66
  • 97
TheRuler
  • 400
  • 2
  • 8