开发者

How do I.. get a value for time at 9:00am local, regardless of the timezone?

开发者 https://www.devze.com 2022-12-25 20:10 出处:网络
In my app, I need to set a variable for a start time to be 9:00 a.m. local, wherever the user is located.

In my app, I need to set a variable for a start time to be 9:00 a.m. local, wherever the user is located.

I have a timezone variable for each user and the save an开发者_运维百科d retrieve are all working. But I need to set a variable when I create a new event to be 9:00 am in the user's local time zone.

My current method uses the local time of the server, then makes the adjustments for the individual user's time zone. I don't know what I don't know - is there a command to create the value for "Today's date at 9:00 am where you are"?

My current code is:

t = Time.now.to_date.beginning_of_day + 11.hours

(forcing the 2 hour offset between my primary user and the server in a different timezone).


Have you considered the Ruby Timezone Library (TZInfo)? It is DST-aware and more fleshed out than Rails' built-in TimeZone class.

You would need to use your knowledge of the user's timezone. A simple example is here:

require 'tzinfo'
tz = TZInfo::Timezone.get('America/New_York')
local = tz.utc_to_local(Time.utc(2010,4,8,9,0,0))

Thus, the local time of 9:00am in EST/EDT is expressed as 05:00 UTC.

irb(main):004:0> local.hour
=> 5


Ruby has a time class which maps to a time class in most databases. In most databases including mysql, it is represented as HH:mm:ss so the date portion is ignored.

The time should always remain the same (09:00) unless it is changed externally. You could fetch this time components using t.hour, and t.min, and construct a Date object with the correct date/time and the adjust for the users timezone.

>> t = Time.parse("09:00")
=> 2010-04-07 09:00:00 -0700
>> t.hour
=> 9
>> t.min
=> 0
0

精彩评论

暂无评论...
验证码 换一张
取 消