我有一个模型Coupon
与属性expired_at
,类DateTime
和我保存记录之前,我想根据用户的选择更改该字段的区域部分。再说了,如何更改TimeWithZone对象的时区?
c = Coupon.new
c.expired_at = DateTime.now
c.expired_at_timezone = "Arizona"
c.save!
而且在coupon.rb
:
class Coupon < ActiveRecord::Base
def before_save
# change the zone part here, leave the date and time part alone
end
end
我想说,如果管理员想要的优惠券在过期2014-07-01 10:00 am
是,亚利桑那时间,存储在数据库中expired_at
应该是这样的:
Tue, 01 Jul 2014 10:00:00 MST -07:00
有没有什么办法可以修改区域部分而只保留日期和时间部分?
感谢
是有可能重写expired_at方法coupon.rb? def expired_at super.in_time_zone(expired_at_timezone) end – leomayleomay 2010-03-09 09:38:10
我用'expired_at'方法更新了我的答案。要获取'expired_at'的当前值,您必须访问'attributes'哈希值。 – 2010-03-09 10:00:53
in_time_zone不会仅更改时区部分。这不是关于作者提问的答案。 – Pencilcheck 2013-07-13 14:43:12