LoginSignup
1
1

More than 5 years have passed since last update.

Time型カラムに記録された時間インスタンスの、平均時刻を取得する(日付は無視)

Posted at

例えば営業終了時刻の:time_shop_closedカラムをもつDailyReportモデルがあり、特定の検索条件で抽出した@daily_reportsインスタンスに対し、viewで以下のようなコードを記述します。

<%second_sum=@daily_reports.pluck(:time_shop_closed).map{
    |x| x.hour*60+x.min
    }.inject(:+)/ @daily_reports.count%>

<%=second_sum.div(60).to_s+"時"+second_sum_average.modulo(60).to_s+"分"%>

単純に時刻インスタンスの配列全てを.to_fメソッドで数値化して、足して、配列数で割ればいいと思ったてたら、大違いでした。

ハマったので記録。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1