Ruby DateTime and epoch conversion



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

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:32]]

有没有办法把这个DateTime转换成划时代的时间,或者用这样的方式来获取划时代时间,而不是像这样获取DateTime?

有没有一种方法可以把划时代的时间转换成这种"时间";2022年1月17日18:03:20 IST+05:30";日期时间格式?

我需要将params[:created_at]与我从DB获得的数据进行比较,这是划时代的。

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

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

如果您喜欢在epoch时间中比较两个日期,您可以从数据库本身选择created_at作为epoch时间,然后您可以通过代码进行比较。对于MySQL数据库,您可以尝试

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

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

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

最新更新