Ruby DateTime and epoch conversion

Viewed 269

I'm using pluck to get the datetime.

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

it is giving me output in this format [[17 Jan 2022 18:03:20 IST +05:30], [20 Jan 2022 13:06:25 IST +05:30]]

Is there way to convert this DateTime in epochtime, or use pluck in such a way to get epochtime instead of getting DateTime like this?

Is there a way to convert epochtime into this "17 Jan 2022 18:03:20 IST +05:30" DateTime format?

I need to compare params[:created_at] which is in epochtime from the data which I'm getting from DB.

2 Answers

To compare dates, you can convert the epochtime in params to time object using Time.at function as follows.

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

If you prefer comparing both dates in epoch time, you can select the created_at as epoch time from database itself and then you can compare it through your code. For MySQL database, you can try

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

Convert to Time with .to_time and then to Unix Time with to_i. For example:

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