Часовой пояс Rails также не перекрывает - PullRequest
1 голос
/ 20 октября 2011

У меня шумные проблемы с UTC в моем проекте Rails.

class ApplicationController < ActionController::Base
   before_filter :set_timezone

   def set_timezone
     Time.zone = current_user.time_zone if current_user
   end

Круто.Я переопределил часовой пояс.И теперь часовой пояс сервера +3.Часовой пояс пользователя +5.Я надеюсь, что любые запросы к Time должны получить часовой пояс пользователя, но этот код возвращает непредвиденные значения:

render :text => Time.zone.to_s + "<br/>" +
                Time.now.to_s + "<br/>" +
                Time.now.in_time_zone.to_s

РЕЗУЛЬТАТ:

(GMT+05:00) Tashkent
Thu Oct 20 19:41:11 +0300 2011
2011-10-20 21:41:11 +0500

Откуда приходит смещение +0300?

Ответы [ 2 ]

1 голос
/ 27 октября 2011

саха! Извините, но у меня нет 15 пунктов репутации, чтобы повысить ваш уровень)). В любом случае спасибо за вашу помощь. Я написал помощник TimeUtil, который использует его для коррекции времени. Это мой текущий псевдокод:

class RacesController < ApplicationController
  def create
    @race = Race.new(params[:race])
    @race.correct_time_before_save   #can be before_save
    @race.save
  end

class Race < ActiveRecord::Base
  def correct_time_before_save
    date = self.attributes["race_date"]
    time = self.attributes["race_time"]
    datetime = Time.local(date.year, date.month, date.day, time.hour, time.min, time.sec)
    datetime_corrected = TimeUtil::override_offset(datetime)
    self.race_date = datetime_corrected.to_date
    self.race_time = datetime_corrected.to_time
  end

# TimeUtil is uses for time correction. It should be very clear, please read description before using.
# It's for time correction, when server's and user's time zones are different.
# Example: User lives in Madrid where UTC +1 hour, Server had deployed in New York, UTC -5 hours.
# When user say: I want this race to be started in 10:00.
# Server received this request, and say: Okay man, I can do it!
# User expects to race that should be started in 10:00 (UTC +1hour) = 09:00 UTC+0
# Server will start the race in 10:00 (UTC -5 hour) = 15:00 UTC+0
#
# This module brings the workaround. All that you need is to make a preprocess for all incoming Time data from users.
# Check the methods descriptions for specific info.
#
# The Time formula is:
#                       UTC + offset = local_time
#                    or
#                       UTC = local_time - offset
#

module TimeUtil

# It returns the UTC+0 DateTime object, that computed from incoming parameter  "datetime_arg".
# The offset data in "datetime_arg" is ignored - it replaces with Time.zone offset.
# Time.zone offset initialized in ApplicationController::set_timezone before-filter method.
#
def self.override_offset datetime_arg      
  Time.zone.parse(datetime_arg.strftime("%D %T")).utc
end

Методы ActiveRecord также адаптированы к часовым поясам пользователя. Время хранится в базе данных (mysql) в формате «utc + 0», и мы хотим получить это время в формате часового пояса текущего пользователя:

class Race < ActiveRecord::Base
  def race_date
    date = self.attributes["race_date"]
    time = self.attributes["race_time"]
    datetime = Time.utc(date.year, date.month, date.day, time.hour, time.min, time.sec).in_time_zone
    datetime.to_date
  end

  def race_time
    date = self.attributes["race_date"]
    time = self.attributes["race_time"]
    datetime = Time.utc(date.year, date.month, date.day, time.hour, time.min, time.sec).in_time_zone
    datetime.to_time
  end
1 голос
/ 20 октября 2011

Чтобы получить текущее время в текущем часовом поясе, вы можете использовать

Time.zone.now

Часовой пояс вашего сервера: +3 и

Time.now.to_s   is returning this 
...