Reputation: 7280
I am using the following functions to get orders in hast 3/half hours:
def send_last_3hours_ordered_sku
time = k = 3.hours.ago.strftime("%Y-%m-%d").to_time + 5.hours + 30.minutes # for IST time
title = "Sku Ordered since (#{time.to_s})"
os = Order.where("completed_at > ?", time).where("state = 'complete'")
Notification.send_email_to_help({:title => title, :attachment_name => title+".csv", :attachment => Admin::OrderQueryController.make_sku_csv(os)}).deliver
end
def send_last_half_hour_ordered_sku
time = k = 0.5.hours.ago.strftime("%Y-%m-%d").to_time + 5.hours + 30.minutes # for IST time
title = "Sku Ordered since (#{time.to_s})"
os = Order.where("completed_at > ?", time).where("state = 'complete'")
Notification.send_email_to_help({:title => title, :attachment_name => title+".csv", :attachment => Admin::OrderQueryController.make_sku_csv(os)}).deliver
end
The function for 3 hours works fine, but the one for half hours does not. Instead of orders completed in the last half hour, it returns all the orders in that day.
I also tried using:
#1.
time = k = 30.minutes.ago.strftime("%Y-%m-%d").to_time + 5.hours + 30.minutes # for IST time
#this gives the same result
#2.
time = k = 30.mins.ago.strftime("%Y-%m-%d").to_time + 5.hours + 30.minutes # for IST time
#This gives an error : undefined method `mins' for 30:Fixnum
Upvotes: 1
Views: 1081
Reputation: 416
The rule of thumb is that rails can handle time zones on it's own, but it tends to be tricky in practice, where sometimes DB is not utc etc. Rule of thumb is that something as simple as:
Order.where("completed_at > ?", 30.minutes.ago.to_s(:db)).where(state: 'complete')
should work for you.
If you still get wrong time, you might try solution from this article - (it might help you understand the workings of the time zones in rails) http://chris.finne.us/2011/09/23/rails-3-tosdb-when-database-time-is-not-utc/
Upvotes: 0
Reputation: 1062
Instead of,
time = k = 0.5.hours.ago.strftime("%Y-%m-%d").to_time + 5.hours + 30.minutes
use
time = k = 30.minutes.ago.in_time_zone(TZInfo::Timezone.get('Asia/Kolkata'))
Upvotes: 2