[英]What's the best way to convert a Date to a DateTime in the current timezone in Rails 4?
我正在使用Rails 4.2。 我有一個Date
,我想轉換為DateTime
。 如果我使用現有的to_datetime
方法,它會在GMT中轉換它。 (我現在已經看了大約一個小時的線程,並且找不到這個確切的問題,所以如果它存在,請提前道歉!)
irb(main):030:0> Date.current
=> Wed, 19 Aug 2015
irb(main):031:0> Date.current.to_datetime
=> Wed, 19 Aug 2015 00:00:00 +0000
如果我然后嘗試使用in_time_zone
,它會將其轉換為當前時區,但也會從日期中減去偏移量。
irb(main):032:0> Date.current.to_datetime.in_time_zone
=> Tue, 18 Aug 2015 17:00:00 PDT -07:00
如何將現有Date
轉換為當前時區的DateTime
時間?
這是我能想到的最佳答案。
Time.zone.at(Date.current.to_time).to_datetime
我有類似的問題,我這樣做了:
Time.use_zone("Europe/Berlin") do
midnight = Time.zone.parse(@date.to_s)
end
這基本上是在目標時區,午夜時間內重新創建日期作為時間實例,而不會“移動”時間實例。
接受的答案對我不起作用,因為Date.current.to_time
將日期轉換為我的:local
時區,即UTC,而不是我配置的時區,即PST。
相反,我使用Date.current.in_time_zone.to_datetime
,我在這里找到: https : Date.current.in_time_zone.to_datetime
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.