Reputation: 45
Never dealt with timezones before. Haven't heard pleasant things.
I am pulling Tweets from a Twitter account to post on an application. I am using the following line of code to display the date as follows: November 26th, 2015.
<%= Date::MONTHNAMES[tweet.created_at.month] %> <%= tweet.created_at.day.ordinalize %>, <%= tweet.created_at.year %>
However, the time is displayed as +0600 further into time than my current location. I am located in Canada/US Central which is -0600. All my local records are correct (both in time and timezone), but I assume this is different because I am pulling it from a non-local source.
2015-11-27 03:07:04 +0000
is the date displayed from the created_at
property of the tweet.
I am wanting to change the tweet's time so that is correct for my timezone at minimum, if not too hard to do I'd prefer it to be compatible with all timezones.
Upvotes: 1
Views: 492
Reputation: 5037
ActiveRecord keeps track of time zones and stores all times as UTC in the database. In you're code you're retrieving that time from the database, but using a very non-standard way to output it which is bypassing ActiveRecord's time zone conversion.
you can try this
tweet_time = tweet.created_at.in_time_zone
tweet_time.strftime("#{tweet_time.day.ordinalize} %B, %Y")
to get the time in your server's timezone, which can be configured in config/application.rb
have a look here and here for more information on working with time zones
In order to get each user to see the time in their own zone you need to capture each user's timezone, then can do this in your action controller
around_filter :user_time_zone, :if => :current_user
def user_time_zone(&block)
Time.use_zone(current_user.time_zone, &block)
end
Upvotes: 0
Reputation: 34328
You can use in_time_zone method to convert the time to your desired timezone:
created_at = '2015-11-27 03:07:04 +0000'
created_at.in_time_zone('Central Time (US & Canada)')
# => Thu, 26 Nov 2015 21:07:04 CST -06:00
Upvotes: 2