I am building a Rails 5.2 app.
In this app I am creating an Automation (if this, then that) feature. When a user creates an Action within the Automation they can set a delay (before the Action can be executed). They set the following:
- Amount (string in DB)
- Type (hours, days, weeks, months)
I use the Rails functionality for this (like 10.days.from_now). I build this date from strings to get the date they selected. I do it like this and it works fine:
date = event.delay_amount.to_i.send(event.delay_type).from_now
Now, this date is relative to another date. For example the created_at date for a Project object. I want to make a method to check if the above constructed date is less than the Project created_at and I do it this way:
def handle_time_period(event)
if event.is_conditioned && event.delay_amount != "0"
date_current = Time.current.to_i
date_constructed = event.delay_amount.to_i.send(event.delay_type).from_now.to_i
date_constructed > date_current ? true : false
else
true
end
end
I got two questions regarding this.
- How can I make sure that they are both in the same timezone? The one from the database (Project created_at I think must be UTF) but the constructed one I don't know.
- How can I compare these two dates in hours, days, weeks or months?
CodePudding user response:
- For simple comparison, use
object.created_at.zone.eql? object2.created_at.zone
To cast to the same timezone, you can useTime.parse(object.created_at).in_time_zone(object2.created_at.zone)
- You can convert your date to UNIX time format,
object.created_at.to_i - object2.created_at.to_i
is the difference in seconds, if necessary, you can calculate in hours and days by dividing by 60 and then by 24. I suggest immediately using the calculation in modules , since we do not know in advance which object was created later.