RahulOnRails
RahulOnRails

Reputation: 6542

ROR + Ruby Date Decrease by 15 minutes

If I have @time = Time.now.strftime("%Y-%m-%d %H:%M:%S"),

How can I reduce this time by 15 minutes ?

I already tried this one :: @reducetime = @time-15.minutes, works fine at console but give errors while execution. Other than this Is there any way to resolve this issue.

Thanks

Upvotes: 0

Views: 466

Answers (1)

mu is too short
mu is too short

Reputation: 434785

Your problem is that you're formatting your time into a string before you're done treating it as a time. This would make more sense:

@time       = Time.now
@reducetime = @time - 15.minutes

# And then later when you're reading to display @time...
formatted_time = @time.strftime("%Y-%m-%d %H:%M:%S")

You shouldn't format your data until right before you're ready to display it.

If you must have @time as the formatted time then you're going to have to parse it before computing @reducetime:

@reducetime = (DateTime.strptime(@time, "%Y-%m-%d %H:%M:%S") - 15.minutes).to_time

Upvotes: 3

Related Questions