You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby on Rails如何便捷计算指定日期范围内的会议总时长?

实现方案

步骤1:修改Meeting模型,新增范围查询和总时长统计方法

在app/models/meeting.rb中添加以下代码:

# 筛选指定日期范围内的会议(按会议开始时间匹配)
scope :in_date_range, ->(start_date, end_date) {
  where("start_time >= ? AND start_time < ?", start_date.beginning_of_day, end_date.end_of_day)
}

# 计算所有符合条件会议的总时长(单位:秒)
def self.total_duration
  sum("(end_time - start_time)").to_i
end

# 原有单场会议时长方法保留
def duration
  (end_time - start_time).to_i
end

步骤2:优化Helper方法,支持总秒数格式化

在app/helpers/meetings_helper.rb中修改为以下代码:

# 原有单场会议时长显示方法保留,复用通用格式化逻辑
def duration_display(meeting)
  seconds_to_en_hm(meeting.duration)
end

# 通用秒数转英文时分格式
def seconds_to_en_hm(total_seconds)
  duration = ActiveSupport::Duration.build(total_seconds).parts
  format('%02d hours and %02d minutes', (duration[:hours]||0), (duration[:minutes]||0))
end

# 通用秒数转中文时分格式,用于总时长输出
def seconds_to_cn_hm(total_seconds)
  duration = ActiveSupport::Duration.build(total_seconds).parts
  "#{duration[:hours] || 0}小时#{duration[:minutes] || 0}分钟"
end

步骤3:控制器中添加统计逻辑

在app/controllers/meetings_controller.rb的index动作中新增统计逻辑:

def index
  @meetings = Meeting.all
  # 支持传入date参数指定统计日期,默认统计当日
  @target_date = params[:date] ? Date.parse(params[:date]) : Date.today
  # 单日会议列表
  @daily_meetings = Meeting.in_date_range(@target_date, @target_date)
  # 单日总时长
  @daily_total = @daily_meetings.total_duration
  # 周度统计(按周日为周起始)
  @week_start = @target_date.beginning_of_week(:sunday)
  @week_end = @target_date.end_of_week(:sunday)
  @weekly_total = Meeting.in_date_range(@week_start, @week_end).total_duration
end

步骤4:视图层输出统计结果

修改app/views/meetings/index.html.erb:

<table>
  <thead>
    <tr>
      <th>Start Time</th>
      <th>End time</th>
      <th>Duration</th>
    </tr>
  </thead>
  <tbody>
    <% @daily_meetings.each do |meeting| %>
    <tr>
      <td><%= meeting.start_time.strftime("%Y-%m-%d %H:%M:%S") %></td>
      <td><%= meeting.end_time.strftime("%Y-%m-%d %H:%M:%S") %></td>
      <td><%= duration_display meeting %></td>
    </tr>
    <% end %>
  </tbody>
</table>

<p><%= @target_date.strftime("%Y-%m-%d") %>当日总会议时长为<%= seconds_to_cn_hm(@daily_total) %></p>
<p>本周总会议时长为<%= seconds_to_cn_hm(@weekly_total) %>(按周日到周日统计)</p>

注意事项

请确保你项目的时区配置正确,在config/application.rb中配置对应时区避免日期统计偏差,比如国内使用可以添加:

config.time_zone = "Beijing"

内容的提问来源于stack exchange,提问作者Sarah Duffy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 09:06:01