How to create a new DateTime object in a specific time zone (preferably the default time zone of my app, not UTC)?

ⅰ亾dé卋堺 提交于 2019-12-21 03:09:09

问题


I have set the time zone in /config/application.rb, and I expect all times generated in my app to be in this time zone by default, yet when I create a new DateTime object (using .new), it creates it in GMT. How can I get it to be in my app's time zone?

/config/application.rb

config.time_zone = 'Pacific Time (US & Canada)'

irb

irb> DateTime.now
=> Wed, 11 Jul 2012 19:04:56 -0700 

irb> mydate = DateTime.new(2012, 07, 11, 20, 10, 0)
=> Wed, 11 Jul 2012 20:10:00 +0000                    # GMT, but I want PDT

Using in_time_zone doesn't work because that just converts the GMT time to PDT time, which is the wrong time:

irb> mydate.in_time_zone('Pacific Time (US & Canada)')
=> Wed, 11 Jul 2012 13:10:00 PDT -07:00               # wrong time (I want 20:10)

回答1:


You can use ActiveSupport's TimeWithZone (Time.zone) object to create and parse dates in the time zone of your application:

1.9.3p0 :001 > Time.zone.now
 => Wed, 11 Jul 2012 19:47:03 PDT -07:00 
1.9.3p0 :002 > Time.zone.parse('2012-07-11 21:00')
 => Wed, 11 Jul 2012 21:00:00 PDT -07:00 



回答2:


Another way without string parsing:

irb> Time.zone.local(2012, 7, 11, 21)
=> Wed, 07 Nov 2012 21:00:00 PDT -07:00



回答3:


If I have it, I usually just specify the utc_offset when instantiating Time.new or DateTime.new.

[1] pry(main)> Time.new(2013,01,06, 11, 25, 00) #no specified utc_offset defaults to system time
 => 2013-01-06 11:25:00 -0500
[2] pry(main)> Time.new(2013,01,06, 11, 25, 00, "+00:00") #UTC
 => 2013-01-06 11:25:00 +0000
[3] pry(main)> Time.new(2013,01,06, 11, 25, 00, "-08:00") #PST
 => 2013-01-06 11:25:00 -0800 



回答4:


This can be achieved in the DateTime class as well by including the timezone.

2.5.1 :001 > require 'rails'
 => true
2.5.1 :002 > mydate = DateTime.new(2012, 07, 11, 20, 10, 0)
 => Wed, 11 Jul 2012 20:10:00 +0000
2.5.1 :003 > mydate = DateTime.new(2012, 07, 11, 20, 10, 0, "PST")
 => Wed, 11 Jul 2012 20:10:00 -0800

or

https://docs.ruby-lang.org/en/2.6.0/DateTime.html

2.6.0 :001 > DateTime.new(2012, 07, 11, 20, 10, 0, "-06")
 => Wed, 11 Jul 2012 20:10:00 -0600
2.6.0 :002 > DateTime.new(2012, 07, 11, 20, 10, 0, "-05")
 => Wed, 11 Jul 2012 20:10:00 -0500



回答5:


I do the following in ApplicationController to set the timezone to the user's time.

I'm not sure if this is what you want.

class ApplicationController < ActionController::Base
  before_filter :set_timezone
  def set_timezone
    # current_user.time_zone #=> 'London'
    Time.zone = current_user.time_zone if current_user && current_user.time_zone
  end

end


来源:https://stackoverflow.com/questions/11444164/how-to-create-a-new-datetime-object-in-a-specific-time-zone-preferably-the-defa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!