Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 198 Vote(s) - 3.53 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do you subtract from a datetime?

#1
I'd like to write a simple function to say in hours:

**How much time has passed since this has been created?**

My attempts:

-time = DateTime.now.hour - (self.created_at.hour)

Does anyone know how to do this in Ruby on Rails?
Reply

#2
Got it!. First you have to make sure your data is in the same data it will be subtracted from whether its a Time or a DateTime. I chose time. Then you divide it by Ruby's built in time methods. This translates into how many days, but it can also be, 1.hour. etc.

(Time.now - self.created_at.to_time)/1.day
Reply

#3
Rails usually uses `Time`, not `DateTime`. Why don't you do `Time.now - self.created_at`? Then you can convert from seconds to hours by dividing by 3600.
Reply

#4
You are looking for the time_ago_in_words(from_time, include_seconds = false) function. Here are some examples from the docs:

time_ago_in_words(3.minutes.from_now) # => 3 minutes
time_ago_in_words(Time.now - 15.hours) # => 15 hours
time_ago_in_words(Time.now) # => less than a minute
from_time = Time.now - 3.days - 14.minutes - 25.seconds # => 3 days


Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through