Rails timestamps, See how much time passed since last time - ruby-on-rails

In my app I want to print out the duration of time I spent from I made the model until I updated it.
So if I have the value
:created_at set to 2016-04-13 14:00:49 UTC
and
:updated_at set to 2016-04-13 15:05:49 UTC
I want to print out that it took 1hour and 5minutes. (or just 01.05).
How do I do this?

I'm not sure why this was downvoted, though a little googling would probably have gotten you to the right answer fairly quickly.
What you're looking for is called time_ago_in_words
Here is the doc http://apidock.com/rails/ActionView/Helpers/DateHelper/time_ago_in_words
And usage is:
time_ago_in_words #object.created_at
time_ago_in_words #object.updated_at
If you want to use it the console to play with it, make sure you preface it with helper so it's loaded into console
e.g.
helper.time_ago_in_words #object.created_at
update
For checking between 2 dates, not just one date from right now, then you can use distance_of_time_in_words
distance_of_time_in_words(#object.created_at, #object.updated_at)
That gives words like
12 days ago
If you're ONLY looking for hours, and nothing else then you can use basic subtraction and division
#object.updated_at.to_i - #object.created_at.to_i) / 60 / 60

You can try this
diff =#object.updated_at.to_time.to_i - #object.created_at.to_time.to_i
hour = "#{diff / 3600}:#{(diff % 3600) / 60}"

Related

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

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
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)
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.
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.

Store seconds in the database - Rails

I have a Timekeeper model in my app. It keeps track of started_at time and finished_at time. I want to take the difference between these two datetimes and pull out the seconds and store that value in the database as an integer. Here is what I'm currently working with.
Method:
((timekeeper.started_at - Time.current) * 24 * 60 * 60).to_i
This returns a value that looks like this : -2336036
The two times above are only 12 seconds apart and I get that value. I'm not sure what it is saying.
The takeaway from my question is: How can I store seconds in the database, between two datetimes that looks similar to what I'm doing currently?
If you want to find the difference between the 2 times you just need to do the subtraction as the difference is returned in seconds.
time.started_at - Time.current
if you dont want the fraction of a second
(time.started_at - Time.current).to_i
and the absolute value
((time.started_at - Time.current).to_i).abs
try the above in a rails console

Rails age of an article in days?

I need to get the age of the article in days. For example, the article was written on Tue, 01 Apr 2014 18:31:07 EDT -04:00 and now I need the days from that date to now printed as an integer. How can I do so?
Please try something like this:
gem install time_diff
install the gem.
require 'time_diff'
time_diff_components = Time.diff(start_date_time, end_date_time)
time_diff_components[:year], time_diff_components[:month], time_diff_components[:week]
This will give more option.
More detail click
This isn't the cleverest way, but it's probably the simplest: use a "magic number": 86400, which is the number of seconds in a day. (you probably already know there are 3600 seconds in an hour, mentally file this number alongside that)
Differences between Time/DateTime objects will be in seconds (as a float). If you divide this by 86400 you get the difference in days, as a float. You can then call to_i on this to get it as an integer if you want.
eg
((Time.now - #article.created_at)/86400).to_i
It's probably worth saving this as a constant, egs SECONDS_IN_A_DAY or something, to avoid mistyping.
With the Date class you can do
(Date.today - #article.created_at.to_date).to_i
to get the number of days between the two dates.

What is a good way to record time periods in Rails application, so that I can easily use them for calculations?

I have time periods like:
2 years
1 month
4 days
I would like to add them to existing records in my DB in a way that I could easily use them for calculations? The type of calculations I would need would be [time_period] - (Time.now - [datetime]) in order to see how much of the time period is left.
Since my periods are quite standard, I was thinking to save the time periods as strings "2-years", "1-month", "4-days" etc. and split them on use. For example "4-days" could become something like this:
4.send("days".to_sym)
What do you think about this method? Any better ideas?
Okay i have a better solution.
Here is the Class TimeDuration
five_minutes = TimeDuration.new("5 min")
five_minutes + Time.now
Time.now
# => 2013-09-13 02:50:06 +0200
five_minutes + Time.now
# => 2013-09-13 02:55:13 +0200
It would be best to store them all in a standardized format; like seconds, so that you can easily do calculations without having to first convert things. If you also stored some sort of units field (i.e. years, days, minutes, seconds), you could then easily convert the seconds back to their appropriate units for display - sort of like what you have above.
stored_value_in_minutes = stored_value.seconds / 1.minutes

Calculating how many 'Midnights' is one date past another in PHP?

I have a start/end times for a calculation I'm trying to do and am having a problem seeing if the end time is before 12AM the day after the start time. Also, I need to calculate how many days past the start time it is.
What I have: Start Date, End Date
What I need:
- How many 'Midnights' is the End Date past the Start Date?
Has anyone done anything like this?
This uses PHP 5.3, if you have an earlier version you may need to use unix timestamps to figure out the difference. The number of midnights should be the number of days difference assuming both start and end times have the same time. So setting both to be midnight of their current day setTime(0,0), should make the calculation correct.
Using the DateTime objects.
$start = new DateTime('2011-03-07 12:23:45');
$end = new DateTime('2011-03-08 1:23:45');
$start->setTime(0,0);
$end->setTime(0,0);
$midnights = $start->diff($end)->days;
Without using the setTime() calls, this would result in 0, because there is less than 24 hours between start and end. With the setTime() this results in 1 because now the difference is exactly 24 hours.
The diff() function was introduced in 5.3 along with the DateInterval class. In 5.2 you can still use the DateTime class but will have to work out the total days using the Unix timestamp.
$midnights = ($end->format('U') - $start->format('U')) / 86400
You can wrap that in an abs() function to the order of start/end does not matter.
Note: These functions may need to be tested for cases that involve DST.
A comment in the php date documentation uses round after dividing by 86400 (number of seconds in a day), to counter any issues that could be involved with DST.
An alternative approach with DateTimes would be to create them in the UTC.
$utcTimezone = new DateTimeZone('UTC');
$start = new DateTime('2011-03-07 12:23:45', $utcTimezone);
$end = new DateTime('2011-03-08 1:23:45', $utcTimezone);

Resources