Categories

Converting Date to Number and then back to Date

I recently implemented a delete file solution in witch I wanted to preserve the file in a trash folder, so I could eventually restore the file. Instead of deleting the file I renamed it and move it to the trash folder. Since a file with the same name could be re-created and then re-deleted, I wanted to make sure that I can preserve all the different versions of the file and and allow restoring any of the previously deleted version.

The solution that I implemented required to add a suffix to the name of the file using the current date and time as a number. Later on I can present a list of the files in the trash folder and convert the date-suffix back to the date and time when the file was deleted, allowing users to choose which version they want to restore.

$file_name = 'my-image.png';
$date = date('Y/m/d H:i:s');
$date_as_number = strtotime($date);
$new_file_name = $file_name . '.' . $date_as_number;
 
echo $file_name ."\n";      // prints: "my-image.png"
echo $date ."\n";           // prints: "2012/11/28 23:51:21"
echo $date_as_number ."\n"; // prints: "1354168281"
echo $new_file_name ."\n";  // prints: "my-image.png.1354168281"
 
// parse the file name and show deleted date
$deleted_date_as_number = array_pop(explode('.', $new_file_name));
$deleted_date_as_string = date('l dS \o\f F Y h:i:s A', $deleted_date_as_number);
$original_file_name = implode('.', array_slice(explode('.', $new_file_name), 0, -1) );
 
echo $deleted_date_as_number ."\n"; // prints: "1354168281"
echo $deleted_date_as_string ."\n"; // prints: "Wednesday 28th of November 2012 11:57:37 PM"
echo $original_file_name ."\n";     // prints: "my-image.png"
 
echo "Do you want to restore the file \"". implode('.', $original_file_name) . "\" deleted on \n$deleted_date_as_string?";
// prints: Do you want to restores the file "my-image.png" deleted on 
// Wednesday 28th of November 2012 11:57:37 PM?