Round Timestamp To Nearest Time With PHP

19th March 2010 - 1 minute read time

If you want to create a "rounded" time stamp, for example, to the nearest 15 minutes use this as a reference:

  1. function roundTime($amount, $units = 'm', $time = null)
  2. {
  3. if (is_null($time)) {
  4. $time = time();
  5. }
  6.  
  7. if ($amount == 0) {
  8. $amount = 1;
  9. }
  10.  
  11. switch ($units){
  12. case 'm':
  13. $roundBy = 60 * $amount;
  14. break;
  15. case 'h':
  16. $time = $time + 60 * 60 * $amount;
  17. $roundBy = 60 * 60 * $amount;
  18. break;
  19. case 'd':
  20. $time = $time + 60 * 60 * 24 * $amount;
  21. $roundBy = 60 * 60 * 24 * $amount;
  22. break;
  23. }
  24.  
  25. return round($time / $roundBy) * $roundBy;
  26. }
  27.  
  28. echo "\n";
  29. echo date('r', roundTime(15, 'm'));
  30. echo "\n";
  31. echo date('r', roundTime(2, 'h'));
  32. echo "\n";
  33. echo date('r', roundTime(3, 'd'));
  34. echo "\n";
  35. echo date('r', roundTime(-3, 'd'));
  36. echo "\n";

Add new comment

The content of this field is kept private and will not be shown publicly.