2

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 Answers2

3

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)
Deepak Kumar
  • 154
  • 5
1

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
DogEatDog
  • 2,899
  • 2
  • 36
  • 65
  • Is there a way to convert epochtime in this format "17 Jan 2022 18:03:20 IST +05:30"(it should contain localtime zone symbol and time difference from UTC, ie IST +05:30)? – shailjakant Jan 08 '22 at 03:09
  • Yes, please take a look at this [answer](https://stackoverflow.com/questions/7816365/how-to-convert-a-unix-timestamp-seconds-since-epoch-to-ruby-datetime). Epochtime is always in UTC, so you'll have to shift the timezone after converting it to a `DateTime` object. – DogEatDog Jan 08 '22 at 03:18