ruby-on-rails Ruby-日期操作以获取数据

bihw5rsg  于 2022-12-15  发布在  Ruby
关注(0)|答案(1)|浏览(184)

我在ruby中有一个需求,我想获取当前月份数据库中的所有数据。然而,有一个陷阱。我想根据计划开始数据获取当前月份的数据。

Ex:
 1. My plan is started on 5th Oct 2022.
 2. Let say, today's date is 3rd Dec 2022. I would want to fetch records from 5th Nov to 3rd Dec.
 3. Let say, today's date is 15th Dec 2022. I would like to fetch records of current cycle that is from 5th Dec till today.

可能有很多种情况,但我的想法是根据当前月份的周期开始日期获取当前月份的记录。
由于我是ruby的新手,有人能告诉我如何使用DateTime或其他相关方法吗?任何帮助都将不胜感激。
型号:

class Customer
  include Mongoid::Document
  include Mongoid::Timestamps
  include SimpleEnum::Mongoid

  field :topic, type: String # This field is to store title/topic
  field :external_uuid, type: String # This represents unique ID
  field :start_time, type: DateTime
  field :duration, type: Integer
  field :created_at, type: DateTime 

  field :random, type: Float, default: -> { rand.round(8) }

  as_enum :type,
          internal: 'internal',
          external: 'external' 
end
ogq8wdun

ogq8wdun1#

根据我的理解,计划开始于每个5号,并且您希望时间跨度从plan_startNOW,您可以使用以下内容获得开始日期

require 'date'

plan_start_day = 5
today = DateTime.now.to_date
puts "Today is #{today}"
puts "Today is day #{today.day} of the month, plan starts on #{plan_start_day}."

start =
    if today.day < plan_start_day 
         DateTime.new(today.year,today.month - 1,plan_start_day)
    else 
         DateTime.new(today.year,today.month,plan_start_day)
    end
puts "Applicable plan start is #{start.to_date}"

今天我们得到一个输出

Today is 2022-12-13
Today is day 13 of the month, plan starts on 5.
Applicable plan start is 2022-12-05

现在,假设您要查找的日期位于start_time列中,即类型为DateTime,您只需查询:

Customer.where('start_time > ? AND start_time < ?', start, today.end_of_day)

当然,created_at也可以工作,因为本列提供了所需的信息... end_of_day的可用性取决于Rails version,但如上所述手动增加应该很容易...
如果您只想使用

Customer.where('start_time > ? AND start_time < ?', start, today.end_of_day).count

现在,我将它作为静态方法添加到Customer模型类中

def self.monthly_sum(date)
    month = (date.day < Customer::PLAN_START_DAY) : date.month - 1 ? date.month 
    plan_start = DateTime.new(date.year, month, Customer::PLAN_START_DAY)
    plan_end = DateTime.new(date.year, month+1, Customer::PLAN_START_DAY)
    Customer.where('start_time > ? AND start_time < ?', plan_start, plan_end).count
end

此方法假设没有“将来”事件,因此它将获取任何日期的完整月份。如果plan_month已经结束,则它将获取完整数据。如果是当前plan_month,则我们获取截至今天的所有数据(因为不存在更新的条目)。
这里的Customer::PLAN_START_DAY是一个常量,如果计划开始是单独的(每个用户、类型、项目......),您需要从相应的记录中获取它,并使用上面介绍的#day方法提取日期。
你现在可以

Customer.monthly_sum(DateTime.now)

或任何适用的日期,并获得匹配的记录数。

相关问题