Search code examples
ruby-on-railsseconds

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?


Solution

  • 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