Amena
Amena

Reputation: 37

calculating hours in between start time and end time

I'm trying to calculate the hours between start time and end time for an event and when a user signs up for an event it goes towards their goals. Right now the method seems to work except I'm getting a negative number. I'm assuming it's something to do with this line of code

h = ((event.start_time - event.end_time) / 1.hour).round

Here's my entire controller for this model hoping someone can help me out with this .

class UserEventsController < ApplicationController

  def create
    event = Event.find(params[:id])
    current_user.events << event
    hours = 0
    goals = current_user.goals
    current_user.events.each do |event|
      h = ((event.start_time - event.end_time) / 1.hour).round
      hours += h
      current_user.update_attributes(hours: h)
    end



    redirect_to organization_path(event.organization)
  end
end

Upvotes: 1

Views: 455

Answers (1)

tadman
tadman

Reputation: 211610

I think you have your times backwards:

h = ((event.end_time - event.start_time) / 1.hour).round

Unless your event ends before it starts that would've produced negative values. Like if it started at 4 and ended at 6 that would be 6-4 or 2 hours, not 4-6.

Upvotes: 1

Related Questions