code_junkie

How to round a time down to the nearest 15 minutes in Ruby

Nov 13th, 2011
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. t = Time.new
  2. rounded_t = Time.local(t.year, t.month, t.day, t.hour, t.min/15*15)
  3.  
  4. require 'activesupport/core_ext'
  5.  
  6. class Time
  7. def round(seconds = 60)
  8. Time.at((self.to_f / seconds).round * seconds)
  9. end
  10.  
  11. def floor(seconds = 60)
  12. Time.at((self.to_f / seconds).floor * seconds)
  13. end
  14. end
  15.  
  16. t = Time.now # => Thu Jan 15 21:26:36 -0500 2009
  17. t.round(15.minutes) # => Thu Jan 15 21:30:00 -0500 2009
  18. t.floor(15.minutes) # => Thu Jan 15 21:15:00 -0500 2009
  19.  
  20. t.min - ( t.min % 15)
  21.  
  22. time.at_beginning_of_last_fifteen_minutes
  23.  
  24. t = Time.new
  25. rounded_t = t-t.sec-t.min%15*60
  26.  
  27. Time.at(t.to_i/(15*60)*(15*60))
  28.  
  29. t = Time.new
  30. truncated_t = Time.at(t.to_i - t.sec - t.min % 15 * 60)
  31.  
  32. min / 15 * 15
  33.  
  34. 15 => 15
  35. 16 => 15
  36. ..
  37. 29 => 15
  38. 30 => 30
  39.  
  40. (( min + 7.5 ) / 15).to_i * 15
  41.  
  42. ( min.to_f / 15 ).round * 15
  43.  
  44. # this is an extension of Ryan McGeary's solution, specifically for Rails.
  45. # Note the use of utc, which is necessary to keep Rails time zone stuff happy.
  46. # put this in config/initializers/time_extensions
  47.  
  48. require 'rubygems'
  49. require 'active_support'
  50.  
  51. module TimeExtensions
  52. %w[ round floor ceil ].each do |_method|
  53. define_method _method do |*args|
  54. seconds = args.first || 60
  55. Time.at((self.to_f / seconds).send(_method) * seconds).utc
  56. end
  57. end
  58. end
  59.  
  60. Time.send :include, TimeExtensions
  61.  
  62. class Time
  63. def round(sec=1)
  64. down = self - (self.to_i % sec)
  65. up = down + sec
  66.  
  67. difference_down = self - down
  68. difference_up = up - self
  69.  
  70. if (difference_down < difference_up)
  71. return down
  72. else
  73. return up
  74. end
  75. end
  76. end
  77.  
  78. t = Time.now # => Mon Nov 15 10:18:29 +0200 2010
  79. t.round(15.minutes) # => Mon Nov 15 10:15:00 +0200 2010
  80. t.round(20.minutes) # => Mon Nov 15 10:20:00 +0200 2010
  81. t.round(60.minutes) # => Mon Nov 15 10:00:00 +0200 2010
Add Comment
Please, Sign In to add comment