why is the datetime in database different when I output it? - ruby-on-rails

In my database on heroku, it shows contactemail.created_at = "2010-08-08 17:16:19"
However, when I use puts.contactemail.created_at I get something different. I get:
2010-08-08 10:11:13 -0700
I need to input that value through an API to another application, and I am pretty sure that the first format is what it wants. If it doesn't take that, it wants 08/08/10 17:16:19 -- in either case, I don't know how to format it properly.
This is in Ruby on Rails.

The display of date is based on your servers locale settings. If you are looking for the first format you could try
puts.contactemail.created_at.to_s(:db)
Have a look at strftime doc here http://ruby-doc.org/core/classes/Time.html#M000298 to get the second format
HTH

Ruby on rails can manage different time zones.
You can:
Make a direct sql consult (rails have some helpers)
Make that the two dates be equals, configuring config.active_record.default_timezone

Related

List the time zones for a Country

I am looking for the code that displays list of countries/regions in ruby on rails when selecting a specific country/region, it displays the time zone of it. For example when i choose “United Kingdom" as country/region then it should displays “(GMT +00:00)London" as Time Zone. My application runs on Rails 3.2.11. I am displaying all the countries using countries gem and all the time zones using ActiveSupport::TimeZone. I want to know if Ruby on Rails provide this functionality by default or if there is any other possible way to achieve this.
In Rails 5.2 this is simple: ActiveSupport::TimeZone.country_zones("US")
You can use TimeZone class. You can get all timezones list by:
zones_hash = ActiveSupport::TimeZone::MAPPING
And you can get time zone of any country as the following:
country_zone = ActiveSupport::TimeZone.new("Europe/Skopje")
country_zone.formatted_offset
The output: +01:00 for the above example.

How to get tzinfo from ActiveSupport::TimeZones.zones_map?

I'm trying to retrieve an array of all time zones tzinfo but I only need the "America/Los_Angeles" part from each so I can validate timezones being received from an iOS mobile client. Currently running the following:
ActiveSupport::TimeZone.zones_map.values.collect { |z| z.tzinfo }
I get the class TZInfo::TimezoneProxy along with the info I need.
Try following code:
ActiveSupport::TimeZone::MAPPING.values
The zones in ActiveSupport::Timezones are limited to a subset of 146 "meaningful" zones, though they do not define by what critera they determine which zones are "meaningful".
If you use it to validate IANA time zone identifiers coming from another platform, you will certainly have false negatives, as there are over 500 of them.
Instead, use the TZinfo Gem directly, rather than Rail's strange mutated version of it. See also the section on Rails Time Zone Identifiers in the timezone tag wiki.
Found the instance method "identifier" in the documentation - http://www.rubydoc.info/gems/tzinfo/TZInfo/TimezoneProxy#_load-class_method
So all I needed was
ActiveSupport::TimeZone.zones_map.values.collect{|z| z.tzinfo.identifier }

Formatting Date according to user profile settings

Each user of our application can have different format for Date and Time. I understand the date format is dependent on user's language and possibly time zone.
I guess I can try to run something like Date::DATE_FORMATS[:default] = "%m/%d/%Y" in ApplicationController. In this case Date.today.to_s would return the property formatted date. Will it be thread safe?
Another option I am looking at is to store profiles into config/locales/en.yml with different keys like en_US, en_GB, en_... and store locale name into the user's profile. In this case I will need to use I18n.localize to format the date. Is it possible to fall back to en if there is no key found in specific en_US?
In the case of Date::DATE_FORMATS or TIME::DATE_FORMATS, you will need to take extra care to make their usage threadsafe, unfortunately. Shouldn't be too difficult to do, however.
AS for your second question, I believe you are concerned with locale fallbacks, and the i18n gem has support for locale fallbacks. This feature is easily enabled with:
I18n::Backend::Simple.include(I18n::Backend::Fallbacks)

Rails 3 ui datepicker

I have some strange behavior in my rails3 app.
When I pick a date with jquery UI datepicker. I see this in my log
Parameters: {"commit"=>"Save", "log"=> {"log_date"=>"04/20/2011"} ....blah...b}
AREL (1.0ms) INSERT INTO "logs" ("log_date") VALUES ('2011-04-19 22:00:00.000000')
I've left out the irrelevant information.
As you see Rails does not translate the date inputted correct. It changes (in this case) 20.apr to the 19.apr.
When I later call
<%= log.log_date.strftime('%d.%m.%y') %>
I get the corect date, but when I do this query
#log_times = Log.group(:log_date)
The logs are all one day earlier than they sould be.
In the console the log in this example looks like this
irb(main):017:0> Log.last
=> [#<Log id: 246, log_date: "2011-04-19 22:00:00">]
So, its save one date to early, but when I show it in the view it's correct.
Why?
Could I use a getter and setter to fix this?
Rails is built to handle timezones by default. Times stored in the database are stored in UTC and Rails is supposed to handle translating that into the configured local time automatically.
Do you have config.time_zone set in your application.rb file? Also, I'd recommend using DateTime rather than Time when possible.

How do I work with Time in Rails?

I've been pulling my hair out trying to work with Time in Rails. Basically I need to set all time output (core as well as ActiveSupport) to the server's local time -- no GMT, no UTC, etc. I've seen various posts relating to Time, but they usually involve someone's need to set it for each user. Mine isn't nearly as complex, I simply want consistency when I use any Time object. (I'd also appreciate not receiving errors every 3 seconds telling me that I can't convert a Fixnum (or some other type) to string -- it's Ruby, just do it!)
I also seem to be getting drastically different times for Time.new vs the ActiveSupport 1.second.ago. Anyway, does anyone have any quality suggestions as regards working with Time in Rails?
If you just want Time objects to be consistent, then why not stick with UTC? I just tried Time.new and 1.second.ago using script/console and I get the same output (give or take a second for typing the command). How are you doing it?
Somewhere in your initializers, define the format(s) that you want to use.
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(:default => '%m/%d/%Y %H:%M')
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(:my_special_format => '%H:%M %p')
Then when you want to print a Time object, it works like the following example. Notice that the Time object in my console is already aware of my time zone. I'm not performing any magical transformations here.
>> t = Time.now
=> Wed Jul 15 18:47:33 -0500 2009
>> t.to_s
=> "07/15/2009 18:47"
>> t.to_s(:my_special_format)
=> "18:47 PM"
Calling Time#to_s uses the :default format, or you can pass in the name of the format you'd rather use like I did with :my_special_format.
You can see the various options for formatting a Time object here.
If u don't want to store each user time setting, the only solution is to use javascript time system because it work on user client time. For example i have an application that each time user try it, the app will create some example data with each data have a initial date value "today". At first time, it confuse me a lot because my host server is in australia and lot of user is on western part, so sometime the initial date value is not "today", it said "yesterday" because of different time region.
After a couple day of headache i finally take decision to JUST use javascript time system and include it in the link, so when user click the "try now" link it will also include today date value.
<% javascript_tag do -%>
var today = new Date();
$("trynow").href = "<%= new_invitation_path %>?today=" + today.toLocaleString();
<% end -%>
Add the following to config/environment.rb to handle time correctly and consistently all the time within the context of Rails. It's important to know that it will store your times to the database in UTC -- but this is what you want -- all the conversion is done automatically.
config.time_zone = 'Pacific Time (US & Canada)'
You can run rake time:zones:local from your Rails root directory to get a list of valid time zone strings in your area.
A quick addition to the DATE_FORMAT solution posted above. Your format can be a string, in which case it works as noted above by calling strftime, but you can also define the format as a lambda:
CoreExtensions::Time::Conversions::DATE_FORMATS.merge! :my_complex_format => lambda {|time|
# your code goes here
}

Resources