开发者

Getting local time

开发者 https://www.devze.com 2023-01-09 09:04 出处:网络
I\'ve got this time stored as a string: 2010-07-25 04:16:25 This is the GMT time for some action I took.

I've got this time stored as a string:

2010-07-25 04:16:25

This is the GMT time for some action I took.

Since I live in the Jerusalem time zone, I would like to show it at Jerusalem time, i.e. 07:16 in the morning, not the GMT time of 04:16:25 which is 3 hours before.

How do I properly convert it programmatically with Ruby on Rails? I seem to get lost with the multitude of timezone functions and considerations I need to take when serving users from different locations.

I tried: Time.parse("2010-07-25 04:16:25") a开发者_高级运维nd it gave me: "Sun Jul 25 04:16:25 +0300 2010".

I suppose the "+0300" is the difference to where I'm at?

Some light on this, or even a link to a good article that doesn't assume you know much, would help.


You can define your timezone in environment.rb file (if you are using Rails 2.3.*) or application.rb (if you're using Rails 3).

Just look for section about time zones and everything is explained in comment. It will say something like this (this is from Rails 3):

# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'

Just uncomment that last line and you should be fine.


To configure it easily related to your system local zone you can add this in your application.rb

config.time_zone = Time.now.zone

and you can use something like this to get the localtime

Post.created_at.localtime
0

精彩评论

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