我正在使用 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]]
有沒有辦法在 epochtime 中轉換這個 DateTime,或者以這種方式使用 pluck 來獲取 epochtime 而不是像這樣獲取 DateTime?
有沒有辦法將 epochtime 轉換為這種“2022 年 1 月 17 日 18:03:20 IST 05:30”日期時間格式?
我需要從我從 DB 獲得的資料中比較處于紀元時間的 params[:created_at]。
uj5u.com熱心網友回復:
要比較日期,您可以使用以下Time.at函式將 params 中的 epochtime 轉換為 time 物件。
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
如果您更喜歡在紀元時間比較兩個日期,您可以從資料庫本身中選擇 created_at 作為紀元時間,然后您可以通過代碼進行比較。對于 MySQL 資料庫,你可以試試
ModelName.where("created_at >=?",Time.zone.now)
.select("UNIX_TIMESTAMP(created_at) as epoch_time")
.map(&:epoch_time)
uj5u.com熱心網友回復:
使用 轉換為時間,.to_time然后使用to_i.轉換為Unix 時間。例如:
created_at = ModelName.where("created_at >= ? ", Time.zone.now).pluck(:created_at)
created_at.to_time.to_i
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/407155.html
標籤:
上一篇:*修改*PermitScrubber默認行為的Rails自定義Scrubber
下一篇:鐘形曲線法重構
