![](/img/trans.png)
[英]How to intercept timezone of a DateTime object and convert it to another timezone (Ruby/Rails)
[英]Convert Ruby on Rails 5 datetime into milliseconds respecting the timezone
我试图将rails datetime转换为毫秒,但是当我调用.strftime
或.to_i
它会忽略分配给它的时区并读取系统的时区
system timezone: Europe/London # currently is +01:00 due to BST
# application.rb
config.time_zone = 'Europe/Athens' # +03:00
stored in database as GMT: 2019-04-19 10:00:00.000000
start_date: schedule.start_date,
to_datetime: schedule.start_date.to_datetime,
strftime: schedule.start_date.to_datetime.strftime('%Q').to_i,
start_date: "2019-04-19T13:00:00.000+03:00",
to_datetime: "2019-04-19T13:00:00.000+03:00",
strftime: 1555668000000, # 2019-04-19T11:00:00.000+01:00
它在视图中正确呈现
<%= schedule.start_date %>
# 13:00:00 19 Apr 2019
irb(main):004:0> Time.at(1555668000)
=> 2019-04-19 11:00:00 +0100
如果之前已经回答过,我很抱歉,但我找不到满意的解决方案。
我最终做了这样的事情
system timezone: UTC
# application.rb
config.time_zone = 'UTC'
然后我实现了一个类似于http://railscasts.com/episodes/106-time-zones-revised的时区切换器
dst = Time.zone.now.dst?
offset = Time.zone.utc_offset
offset += 3600 if dst
ts = (schedule.start_date.to_i + offset) * 1000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.