我正在构建一个应用程序,用户可以在该应用程序中的表单中输入数据,包括日期和时间,然后该应用程序会根据该信息用事件填充他们的 Google 日历。我似乎无法弄清楚如何处理时区,而且我不确定问题是否出在 Ruby/Rails 或 Google Calendar API 上,这两者都有文档……不是很好。
如果我在表单中输入上午 10:00,Google 日历邀请将在上午 6:00 创建。我在 UTC 的 -0400,这说明了这一点。理想情况下,我希望用户根本不必担心时区,但如果我必须让我的用户从下拉列表中选择时区,那也不是世界末日。
这是我的表格(只要我有办法让用户输入时间和日期,我可以以任何方式自由修改):
<%= date_field(:calendar, "start_date", min: Date.today, :value => Time.now.strftime('%Y-%m-%d'), :class=>'form-control') %>
<input type="time" id="calendar_start_time" name="calendar[start_time]" min="9:00" max="18:00" value="10:00" step="900" />
<%= select("calendar", "time_zone", @timezones, {:class=>'form-control'}) %>
还有我的 Controller :
def create
calendar_id = params[:calendar][:id]
start_date = params[:calendar][:start_date]
start_time = params[:calendar][:start_time]
time_zone = params[:calendar][:time_zone]
lesson_hash = get_module_lectures(module_number)
# Time.zone = 'America/New_York'
lesson_hash.each do |days_from_start, lesson_name|
lesson_datetime = Time.parse("#{start_date} #{start_time}").advance(:days => days_from_start)
new_event(calendar_id, lesson_datetime, lesson_name, time_zone)
end
redirect_to calendars_url
end
def new_event(calendar_id, lesson_datetime, lesson_name, time_zone)
client = Signet::OAuth2::Client.new(client_options)
client.update!(session[:authorization])
service = Google::Apis::CalendarV3::CalendarService.new
service.authorization = client
event = Google::Apis::CalendarV3::Event.new({
# start: Google::Apis::CalendarV3::EventDateTime.new(datetime: lesson_datetime),
# end: Google::Apis::CalendarV3::EventDateTime.new(datetime: lesson_datetime.advance(:hours => 1)),
start: {
'date_time': lesson_datetime,
# 'time_zone': 'America/New_York'
},
end:{
'date_time': lesson_datetime.advance(:hours => 1),
# 'time_zone': 'America/New_York'
},
summary: lesson_name
})
service.insert_event(calendar_id, event)
end
如您所见,我已经尝试在几个地方对时区进行硬编码以进行测试,但它们似乎对创建的事件没有任何影响——它们总是偏移 4 小时。我正在使用 Rails 5.2
最佳答案
DateTime 必须与 TimeZone 一起设置:
lesson_hash.each do |days_from_start, lesson_name|
lesson_datetime = ActiveSupport::TimeZone["America/New_York"].parse("#{start_date} #{start_time}").advance(:days => days_from_start)
new_event(calendar_id, lesson_datetime, lesson_name, time_zone)
end
时间需要正确格式化。试试这个:
event = Google::Apis::CalendarV3::Event.new(
start: Google::Apis::CalendarV3::EventDateTime.new(date_time: lesson_datetime.to_datetime.rfc3339),
end: Google::Apis::CalendarV3::EventDateTime.new(date_time: lesson_datetime.advance(:hours => 1).to_datetime.rfc3339),
summary: lesson_name
)
service.insert_event(calendar_id, event)
关于ruby-on-rails - 使用 Google Calendar API 在 Rails 应用程序中处理时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51656061/