2012-03-16 58 views
3

我有一個問題,試圖在JQuery日期/時間選擇器中用Rails處理時區。 datepicker,正確顯示本地時區。問題出現了,當我將選定日期保存到我的數據庫中時,即使時間在客戶端的時區,rails仍將其保存爲UTC時間。當我嘗試將時間轉換爲utc(Time.zone.parse(params [:time])。utc)時,它給出了與params [:time](即本地時間)相同的值。Rails jquery datepicker時區

我不想在environment.rb文件中更改config.time_zone的設置,因爲我不希望將時間保存在服務器的本地時區中。

我想要做的是接收當地時間,並將其轉換爲utc,以便我可以在時間設置爲utc的服務器上安排cron作業。我想節省時間在數據庫中,作爲用戶的本地時區...但我無法找到獲取客戶端時區的方法!

除了在datepicker上添加時區作爲選項,我還有其他選擇嗎?

回答

2

DateTime Picker爲用戶提供正確的時間 - 在此之後,由您來解析時間,調整用戶的時區,並相應地安排您的cron作業,方法是添加或減去適當的小時。以下是我去一下吧:

# convert your param from a datepicker string to time: 

start_time=DateTime.strptime(params[:start_time], "%m/%d/%Y %H:%M:%S").to_time 

# datepicker gives times in UTC to your server *BUT* it appears in the local time to the user. Make sure to adjust for this time difference. 

start_time = start_time.in_time_zone(current_user.time_zone) # I let users pick their time zone. 

# account for DST. does this work? I think so. 
offset = (start_time.utc_offset)/60/60 

# now adjust by the hours offset. you likely want to keep the time in utc for your database... 

adjusted_start_time = (start_time-offset.hours).utc 
從另一個

relavent信息,以便張貼Convert UTC to local time in Rails 3

# Rails has it's own names. See them with: rake time:zones:us To see other zone-related rake tasks: rake -D time 

# So, to convert to EST, catering for DST automatically: 

Time.now.in_time_zone("Eastern Time (US & Canada)")