Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
22
rated 0 times [  27] [ 5]  / answers: 1 / hits: 14407  / 7 Years ago, sun, june 11, 2017, 12:00:00

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.


More From » php

 Answers
4

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

[#20092] Friday, June 9, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
julieth

Total Points: 382
Total Questions: 99
Total Answers: 85

Location: Cape Verde
Member since Fri, Nov 27, 2020
4 Years ago
;