Home > Blockchain >  How to create time property that is always 24 hours behind current time?
How to create time property that is always 24 hours behind current time?

Time:11-30

I am creating a time object, which I use to gather all info from the past 24 hours, I have no issue creating the object displaying the current time. But I am unsure as to how to set it exactly 24 hours in the past, without having the timezone attached.

  def set_time
     @past_time = Time.now.to_s(:db) - 1.days
  end

Expected Output Format :

 "2021-11-29 09:15:17"

Result:

 undefined method `-' for "2021-11-29 10:19:46":String

CodePudding user response:

You are subtracting the time from the string object as you converted Time.now into the string using to_s.

Instead of you can do this

(Time.new - 1.days).to_s(:db)

Note: You will get multiple ways to accomplish these rails. You can improve the code readability and understanding of code by doing this.

Example:

DateTime.now.days_ago(1)

CodePudding user response:

The easiest I can think of would be:

24.hours.ago.to_s(:db)

Note that the returned time would default to UTC in this case.

CodePudding user response:

You can use DateTime#advance from ActiveSupport:

Time.current.advance(hours: -24)
# or 
Time.current.advance(days: -1)

Note that in timezones that use DST a day is not always 24 hours so the two are not actually equivilent. You can also use the methods that ActiveSupport::Duration monkeypatches onto Integer:

24.hours.ago
1.day.ago

This always uses your default timezone though.

  • Related