Home > OS >  Subtract two dates and return it in seconds in the query
Subtract two dates and return it in seconds in the query

Time:11-25

hi everyone im new to rails, I am trying to make a query using 3 parameters

 def zones_by_container
    container_id= params[:container_id]
    start_time = params[:start_time_at]
    end_time = params[:end_time_at]
    container =Container.find(container_id)

    @Zone = Zone.where(customer: container.customer_id,container: container_id, 
    start_time_at: start_time..end_time).select('address, start_time_at, end_time_at, 
    notified_at, end_time_at - start_time_at as `Time`').as_json(:except => :id)
 
    render json: { status: 'Success',data: @zone}

end

I would like the subtraction of the dates to return it in seconds in my query This is an example of my query with the two parameters

 {
        "start_time_at": "2022-11-24 10:10:16",
        "end_time_at": "2022-11-24 10:11:20",
        "Time": 104
    },

I want the result to look like this

 {
        "start_time_at": "2022-11-24 10:10:16",
        "end_time_at": "2022-11-24 10:11:20",
        "Time": 64
    },

Could someone help me so that the subtraction of the two dates comes out in seconds, I have searched and I did not find how to solve this problem

CodePudding user response:

Try with:

select('UNIX_TIMESTAMP(end_time_at) - UNIX_TIMESTAMP(start_time_at) as time')

CodePudding user response:

What about to do it in json file?

(start_date_time - end_date_time).to_f

  • Related