Ruby 日期时间和纪元转换

Ruby DateTime and epoch conversion

我正在使用 pluck 获取日期时间。

ModelName.where("created_at >= ? ", Time.zone.now).pluck(:created_at)

它以这种格式给我输出 [[2022 年 1 月 17 日 18:03:20 IST +05:30],[2022 年 1 月 20 日 13:06:25 IST +05:30]]

有没有办法将这个 DateTime 转换为纪元时间,或者以这种方式使用 pluck 来获取纪元时间而不是像这样获取 DateTime?

有没有办法将纪元时间转换为这种“2022 年 1 月 17 日 18:03:20 IST +05:30”日期时间格式?

我需要比较 params[:created_at],它与我从 DB 获取的数据处于纪元时间。

转换为 Time with .to_time,然后使用 to_i 转换为 Unix 时间。例如:

created_at = ModelName.where("created_at >= ? ", Time.zone.now).pluck(:created_at)
created_at.to_time.to_i

要比较日期,您可以使用 Time.at 函数将参数中的纪元时间转换为时间对象,如下所示。

2.7.3 :011 > Time.at(1641658419)
=> 2022-01-08 21:43:39 +0530 
2.7.3 :011 > Time.at(1641658419) > DateTime.parse("2021-12-01")
=> true

如果您更喜欢以纪元时间比较两个日期,您可以 select created_at 作为数据库本身的纪元时间,然后您可以通过代码进行比较。对于MySQL数据库,你可以试试

 ModelName.where("created_at >=?",Time.zone.now)
.select("UNIX_TIMESTAMP(created_at) as epoch_time")
.map(&:epoch_time)