I wanted to have a formatted time difference function that worked with two time() integer results and formatted the results, such as "X Years, Y Months, Z Weeks, etc.." The following is that function, and it's designed to be modifiable, so you could easily cut out the standard Years / Months / Weeks / Days / Hours / Minutes / Seconds Format, and go to whatever format you prefer in whatever order you prefer.
Note: This is apparently very useful for those using older versions of PHP, where the date_diff function isn't implemented!
<?php
// Define Input
// --------------------------------------
// Example Time Difference
$start_time_for_conversion = 0;
$end_time_for_conversion = 123456;
$difference_of_times = $end_time_for_conversion - $start_time_for_conversion;
$time_difference_string = "";
for($i_make_time = 6; $i_make_time > 0; $i_make_time--)
{
switch($i_make_time)
{
// Handle Minutes
// ........................
case '1';
$unit_title = "Minute(s)";
$unit_size = 60;
break;
// Handle Hours
// ........................
case '2';
$unit_title = "Hour(s)";
$unit_size = 3600;
break;
// Handle Days
// ........................
case '3';
$unit_title = "Day(s)";
$unit_size = 86400;
break;
// Handle Weeks
// ........................
case '4';
$unit_title = "Week(s)";
$unit_size = 604800;
break;
// Handle Months (31 Days)
// ........................
case '5';
$unit_title = "Month(s)";
$unit_size = 2678400;
break;
// Handle Years (365 Days)
// ........................
case '6';
$unit_title = "Year(s)";
$unit_size = 31536000;
break;
}
if($difference_of_times > ($unit_size - 1))
{
$modulus_for_time_difference = $difference_of_times % $unit_size;
$seconds_for_current_unit = $difference_of_times - $modulus_for_time_difference;
$units_calculated = $seconds_for_current_unit / $unit_size;
$difference_of_times = $modulus_for_time_difference;
$time_difference_string .= "$units_calculated $unit_title, ";
}
}
// Handle Seconds
// ........................
$time_difference_string .= "$difference_of_times Second(s)";
// Example Result: "1 Day(s), 10 Hour(s), 17 Minute(s), 36 Second(s)"
?>
One other example: 123456789 = "3 Year(s), 10 Month(s), 3 Week(s), 2 Day(s), 21 Hour(s), 33 Minute(s), 9 Second(s)"
Official Function Page: http://www.php.net/manual/en/function.date-diff.php
// Note: All code appearing on the PHP Revolution blog by the blog owner is released under the Hacktivismo Enhanced-Source Software License Agreement (HESSLA), unless otherwise noted. http://www.hacktivismo.com/about/hessla.php
No comments:
Post a Comment