Recently a friend asked me how I would go about copying a file on his Windows machine to the same directory but append the date to the filename in the standard ISO 8601 format (YYYYMMDD) with the leading zeros, of course. At first I gave him the following answer for a windows batch file:
SET myfile=win.ini
FOR /F "tokens=1-4 delims=/ " %%I IN ('DATE /t') DO SET mydate=%%L%%J%%K
copy %myfile% %myfile%-%mydate
Which got me to thinking of how to do it in some other languages, out of boredom. So here it is in Classic ASP:
<%
file = "win.ini"
set fs=Server.CreateObject("Scripting.FileSystemObject")
fs.CopyFile file, file & "-" & Year(date) & Right(Cstr(100 + Month(date)),2) & Right(Cstr(100 + Day(date)),2)
%>
And the best for last, here it is in PHP:
<?
$file = 'win.ini';
if(!copy($file,$file.'-'.date("YmdHis"))) { echo 'File copy failed'; }
?>
If you can do this in a language not presented here, please submit it in the comments. The goals are:
- to make the code as short as possible
- the source filename must be a variable on it’s own line
- ISO 8601 formatting is required (YYYYMMDD). You may use (YYYYMMDDHHMMSS) as a preferred alternative.