user656213
user656213

Reputation: 1083

Substracting minutes from Time in ruby

I have a string in date-time format "02/22/12 01:04" (24 hour time format) I need to subtract 6 minutes from it. (like subtracting 1 minutes each time using loop) and store it in array all 6 different times. I need to do this in ruby 1.8.7. Could you please help me?

Upvotes: 0

Views: 153

Answers (2)

phoet
phoet

Reputation: 18845

this is a really awefull job in ruby 1.8.7:

require 'time'
require 'date'

6.times.map { |i| Time.parse(DateTime.strptime("02/22/12 01:04", "%m/%d/%y %H:%M").to_s) - i * 60}
# => [Wed Feb 22 02:04:00 +0100 2012, Wed Feb 22 02:03:00 +0100 2012, Wed Feb 22 02:02:00 +0100 2012, Wed Feb 22 02:01:00 +0100 2012, Wed Feb 22 02:00:00 +0100 2012, Wed Feb 22 01:59:00 +0100 2012]

Upvotes: 1

kikuchiyo
kikuchiyo

Reputation: 3421

In rails, you can do this, though I am not sure which Gem in rails allows you to:

# to get 2012, use "02/22/2012"
# note this gives you the year 0012, not 2012.

my_date = "02/22/12 01:04".to_time
my_date_array = []
6.times do
  my_date -= 1.minute
  my_date_array.push(my_date.strftime("%D/%m/%Y %I:%M"))
end

I assumed from the Tags you listed that you need to do this in Rails. Works in Rails 3+ for me, using Ruby 1.8.7.

Upvotes: 2

Related Questions