如何在 Rails 中用 Time.zone.now 覆盖 Time.now [英] How to override Time.now with Time.zone.now in rails

查看:32
本文介绍了如何在 Rails 中用 Time.zone.now 覆盖 Time.now的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我正在做一个 rails 项目.我想要特定区域的时间,我知道我可以使用 Time.zone.now但我想先设置区域,然后想根据区域获取时间.有什么方法可以让我在设置区域后用 Time.zone.now 覆盖 Time.now 方法.

Hello i am working on a rails project. i want the time with specific zone, i know i can use Time.zone.now but i want to first set the zone and then want to get the time based on the zone. is there any way so that i can override the Time.now method with Time.zone.now after setting the zone.

我尝试在 application_controller.rb 中创建一个 before 操作,然后定义区域,但是每当我尝试访问 Time.now 时,它总是返回没有时区的时间.请帮我.提前谢谢.

I have tried to create a before action in application_controller.rb and then define the zone, but whenever i am trying to access Time.now its always returns the time without time zone. please help me. Thanx in advance.

application_controller.rb
def set_current_time_zone
  Time.zone = current_user.time_zone unless current_user.blank?
end

推荐答案

为什么不使用 Time.current?如果您在 config.zoneTime.zone 中设置了时区,它将为您提供时区时间.

Why not use Time.current? It will give you time with timezone if you have the zone set in config.zone or Time.zone.

看例子:

2.5.0 :021 > Time.zone = "Tallinn"
  => "Tallinn" 
2.5.0 :022 > Time.current
  => Wed, 21 Feb 2018 20:37:29 EET +02:00 
2.5.0 :023 > Time.zone = "New Delhi"
  => "New Delhi" 
2.5.0 :024 > Time.current
  => Thu, 22 Feb 2018 00:07:38 IST +05:30 

关于.current方法见对应的apidock和thoughtbot 关于 Ruby 时区.

See the corresponding apidock about .current method and a good article in thoughtbot about Ruby timezones.

这篇关于如何在 Rails 中用 Time.zone.now 覆盖 Time.now的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆