【问题标题】:splite date with Ice_Cube in rails在 Rails 中使用 Ice Cube 分割日期
【发布时间】:2017-06-12 11:02:24
【问题描述】:

我想创建一个 Api,它获取 start_time 和 end_time 以及应该拆分开始时间和结束时间的月份数,并返回一个集合,我可以循环遍历该集合并将数据保存到数据库中。 例如每周日的 14:05 到 18:30。 这就是我所做的一切:

def create_recurring_schedules 数字=0 如果反复出现 schedule = Schedule.new(start_time, end_time: end_time)

    schedule.add_recurrence_rule Rule.weekly

     if month == 12

        dates = schedule.occurrences_between(start_time,  start_time + 1.year) 
     elsif month == 3
        logger.info "################### The 3 month is #{self.s_month} #############################################"
        dates = schedule.occurrences_between(start_time, start_time + 3.month)
     elsif month == 6
        logger.info "################### The 6 month is #{month} ###########################################"
        dates = schedule.occurrences_between(start_time, start_time + 6.month)
     elsif month == 1

     dates = schedule.occurrences_between(start_time , start_time + 1.months)
   end
    dates.each do |date|
      number +=1
      logger.info "################### Start number #{number} #############################################"
      ClinicSchedule.create(user_id: user_id, clinic_id: clinic_id, month: month,
                                  start_time: date.start_time.strftime("%Y-%m-%d %H:%M"),
                                  end_time: date.end_time.strftime("%Y-%m-%d %H:%M"),
                                  date: date.strftime("%Y-%m-%d"), recurring: true,
                                  recurrence_id: recurrence_id)
      logger.info "################### Recurrence ID: "
      logger.info recurrence_id
      logger.info "################### End Recurrence ID ###########################################################"
    end
  end
end

我在这个案例中遇到的问题是:

dates = schedule.occurrences_between(start_time , start_time + 1.months)

当我从四个月后设置 start_time 时,例如 2017-10-13 16:20。它只给出 35 周,而不给出从四个月后开始的 53 周。

【问题讨论】:

  • 你为什么要Time.now+start_time
  • 这是我做过的最疯狂的事情之一,start_time 可以在两个月后。当我单独使用 Time.now 时,它运行良好,我这样做是为了看看发生了什么

标签: ruby-on-rails ruby rubygems ruby-on-rails-5.1 ice-cube


【解决方案1】:

您的问题来自s_time=(Time.now+start_time).to_i。似乎start_timeActiveSupport::TimeWithZone 的一个实例。您正在尝试添加 TimeActiveSupport::TimeWithZone,这可能不是您想要实现的目标。

schedule.occurrences_between 至少需要两个 ActiveSupport::TimeWithZone 实例。因此,您可以这样做:

s_time = Time.zone.now
e_time = s_time + 1.month

schedule.occurrences_between(s_time, e_time)

UPD:实际上,您不需要那么长的带有月份的条件:

schedule.occurrences_between(start_time, start_time + month.months)

而不是定义和递增number 使用#each_with_index

【讨论】:

  • 我这样做了,但我不知道为什么当我设置 start_time + 1.month 时我得到 44 周。我应该是 4 周而不是 44 周
  • “我有 44 周”是什么意思?
  • 我的意思是关于上面的循环,dates.each 做 |date| ==> 循环 44 次,我节省了 44 次
  • 如果你使用schedule.rrule Rule.weekly而不是schedule.add_recurrence_rule Rule.weekly呢?
  • 我得到相同的结果
猜你喜欢
  • 2011-10-17
  • 1970-01-01
  • 2021-05-13
  • 2018-05-11
  • 1970-01-01
  • 1970-01-01
  • 2018-05-01
  • 1970-01-01
  • 2018-08-23
相关资源
最近更新 更多