Rails Json response automatically changes timezeone only on some requests - ruby-on-rails

We have a simple json API in rails 4 that returns the data using jbuilder. One of the fields is a datetime field "date_of_birth" the json formatting is acting strangely. The same request to the API can randomly generate 2 different results
"date_of_birth":"1989-06-14T20:52:00-07:00"
"date_of_birth":"1989-06-15T03:52:00Z"
As you can see the first one is in local time as the other one is in UTC timezone. We have the timezone globally set to "UTC".
this is the line in the jbuilder view that produces the output, nothing special'
json.array!(#patients) do |patient|
json.extract! patient, :id, :first_name, :last_name, :gender, :groups_code, :date_of_birth
end
What could cause this issue?

Rails is doing some pretty clever work with times in order to cover users with different time-zones and server independent hosting location. Basically times are stored in the database in UTC zone, and converted when needed to the local server/or user time zone.
In a standard Rails app you have 3 times zones that can be the same or can be different: Database time zone, default time zone, and user time zone.
Have a look at this very good article that says it all. Then apply the right method to your date_of_birth field while exporting to json
DOs
2.hours.ago # => Fri, 02 Mar 2012 20:04:47 JST +09:00
1.day.from_now # => Fri, 03 Mar 2012 22:04:47 JST +09:00
Date.today.to_time_in_current_zone # => Fri, 02 Mar 2012 22:04:47 JST +09:00
Date.current # => Fri, 02 Mar
Time.zone.parse("2012-03-02 16:05:37") # => Fri, 02 Mar 2012 16:05:37 JST +09:00
Time.zone.now # => Fri, 02 Mar 2012 22:04:47 JST +09:00
Time.current # Same thing but shorter. (Thank you Lukas Sarnacki pointing this out.)
Time.zone.today # If you really can't have a Time or DateTime for some reason
Time.zone.now.utc.iso8601 # When supliyng an API (you can actually skip .zone here, but I find it better to always use it, than miss it when it's needed)
Time.strptime(time_string, '%Y-%m-%dT%H:%M:%S%z').in_time_zone(Time.zone) # If you can't use Time#parse
DON'Ts
Time.now # => Returns system time and ignores your configured time zone.
Time.parse("2012-03-02 16:05:37") # => Will assume time string given is in the system's time zone.
Time.strptime(time_string, '%Y-%m-%dT%H:%M:%S%z') # Same problem as with Time#parse.
Date.today # This could be yesterday or tomorrow depending on the machine's time zone.
Date.today.to_time # => # Still not the configured time zone.

You may have Time.zone = ... set somewhere based on user time zone setting.

I have seen this same problem and have not been able to figure out why it happens. The other answers here seem to be missing the point that which time format is returned is seemingly random, with no changes to code/config whatsoever.
I was able to "fix" this issue by using .to_time.iso8601 my JBuilder block which will force the 1989-06-15T03:52:00Z format.

Related

Is there an elegant way to use the app timezone when running a Rails ActiveRecord aggregate method?

When I use an ActiveRecord object's time field or use pluck on that field, I always (correctly) get back the time in the application's timezone:
> ClaritySurveyData::SurveyResponse.order(:id).first.submitted_at
=> Mon, 17 Sep 2012 09:46:33 PDT -07:00
> ClaritySurveyData::SurveyResponse.order(:id).pluck(:submitted_at).first
=> Mon, 17 Sep 2012 09:46:33 PDT -07:00
However, when a use an ActiveRecord aggregate method on the same field, I (incorrectly) get back the time in UTC:
> ClaritySurveyData::SurveyResponse.minimum(:submitted_at)
=> 2012-09-17 16:46:33 UTC
This bug has been biting me every few years, just infrequently enough that every time I have to figure it out afresh.
Obviously, I can easily work around it in specific cases using .in_time_zone.
However, I'd love to be able to patch it generally, so I don't ever have to figure it out again.
Any suggestions?

Rails Time Zone: How to pass time zone configured in application.rb file as parameter to the to_datetime method?

I configured my time zone to indian time zone in my Rails app by adding this line config.time_zone = 'Mumbai' to my application.rb file.
I am having a date time field t.datetime :check_in in my table. To this check_in column I am saving the server time like this Person.check_in = DateTime.now. When I save like this, the time is saving properly, with the time zone configured in the app. after that for some reason when I update like this Person.check_in = "24/08/2015 11:50 AM".to_datetime it is not saving the time with the time zone I configured. Below is my rails console output:
prashant#prashant-pc:~/client_proj/template$ rails c
Loading development environment (Rails 4.1.5)
2.2.2 :001 > check_in = DateTime.now
=> Mon, 24 Aug 2015 11:41:16 +0530
2.2.2 :003 > "24/08/2015 11:42 PM".to_datetime
=> Mon, 24 Aug 2015 23:42:00 +0000
2.2.2 :004 >
This is unfortunately the designed behavior of to_datetime function.
This other question is what you are after. They provide the following alternatives:
Time.zone.parse('24/08/2015 11:50 AM').to_datetime
or even:
"24/08/2015 11:50 AM".to_datetime.in_time_zone("Mumbai")
Use in_time_zone from ActiveSupport::TimeWithZone
"2015-08-14 14:38".to_datetime.in_time_zone('Mumbai')
=> Fri, 14 Aug 2015 20:08:00 IST +05:30
"2015-08-14 14:38".to_datetime.in_time_zone('Eastern Time (US & Canada)')
=> Fri, 14 Aug 2015 10:38:00 EDT -04:00
Time.now.in_time_zone("Mumbai")
=> Sat, 22 Aug 2015 12:38:32 IST +05:30
Time.now.in_time_zone("Pacific Time (US & Canada)")
=> Sat, 22 Aug 2015 00:08:21 PDT -07:00
Actually, there are several ways to do the same thing e.g. using Time.zone.local, Time.zone.parse etc. See the above link for more examples.
To, answer your exact question, to pass the time_zone configured in your application.rb file, you have to use this:
check_in = DateTime.now
check_in.in_time_zone(Rails.application.config.time_zone).to_datetime
Use local time gem. It will display the time in local time zone no matter where you are.
It is very good solution as you will don't have to call in time zone method every time you show a date in your views. The Gem has very good documentation as well. Visit https://github.com/basecamp/local_time

Set timezone for incoming xml data

I'm getting a datetime field from an API that does not explicitly set its timezone. When I place this into a database it's assuming the datetime must be in GMT, but the timezone is actually in Chicago time. (I say Chicago time, because I'm still unsure if this API factors in DST.) What is the best way for me to convert this time to GMT before adding it to the database?
Here is an XML sample of one of the nodes I'm referring to:
<FromDateTime>2011-03-17 08:00:00</FromDateTime>
In Ruby, I'm using this to add this record to the database.
:starttime => DateTime.parse(row.at_xpath("FromDateTime/text()").to_s),
I think what I need to do is add the difference in hours between CST and GMT to this last Ruby call, right? How would I do that?
Thanks!
Could you use Time instead? DateTime is not Daylight Savings Time aware. Time automatically sets to your local GMT offset for the given date/time and set DST if needed.
irb(main):014:0> require 'time'
irb(main):015:0> Time.parse('2011-03-17 08:00:00')
=> Thu Mar 17 08:00:00 -0400 2011
irb(main):022:0> Time.parse('2011-03-17 08:00:00').dst?
=> true
Here is the case for standard time (I am in EST)
irb(main):025:0> Time.parse('2011-01-17 08:00:00')
=> Mon Jan 17 08:00:00 -0500 2011
irb(main):023:0> Time.parse('2011-01-17 08:00:00').dst?
=> false
If you are using ActiveSupport http://api.rubyonrails.org/classes/DateTime.html you can set to arbitrary time zone:
irb(main):039:0> Time.zone = 'America/Chicago'
=> "America/Chicago"
irb(main):040:0> Time.parse('2011-03-17 08:00:00')
=> Thu Mar 17 08:00:00 -0400 2011

How to convert Date into UTC in MongoMapper & Ruby/Rails?

I added this line of code
self.auth_history.push [start_date, self.coupon_code]
And got this error message
Date is not currently supported; use a UTC Time instance instead.
I also tried start_date.utc, but it didn't work either.
Please help. Thanks.
I got this answer from Seattle Brigade group -
===
I didn't see start_date defined in your code as a key in MongoMapper, so
I'll assume you're creating your own date object, either directly via Ruby,
or wrapped by Rails. As far as I know, and someone please correct me, Mongo
stores dates as UTC time in milliseconds since epoch. So when you define a
key with a :date mapping in MongoMapper, you're wrapping a Time object in
Ruby.
Therefore, if you want to store a date inside of Mongo, and it wasn't
created by MongoMapper, make sure you create a Time object in UTC.
MongoMapper comes with a Date mixin method called to_mongo that you can use.
>> Time.now.utc
=> Fri Jan 28 03:47:50 UTC 2011
>> require 'date'
=> true
>> date = Date.today
=> #<Date: 4911179/2,0,2299161>
>> Time.utc(date.year, date.month, date.day)
=> Thu Jan 27 00:00:00 UTC 2011
>> require 'rubygems'
=> true
>> require 'mongo_mapper'
=> true
>> Date.to_mongo(date)
=> Thu Jan 27 00:00:00 UTC 2011
But watch out for the time change.
>> Date.to_mongo(Time.now)
=> Thu Jan 27 00:00:00 UTC 2011
>> Date.to_mongo(Time.now.utc)
=> Fri Jan 28 00:00:00 UTC 2011
Good luck.
===
And by using
Date.to_mongo(start_date)
it works for me.
First, I think the question title is bad in description. Actually, the difference between different timezone is on Time not on Date. So, it's really not proper to say I want to convert a date to UTC format.
Here is another way in Ruby to convert DateTime to its UTC format:
DateTime.now.new_offset(0)
Here's another option:
Time.at(Date.today.to_datetime.to_i).utc
Here I am using Date.today as an arbitrary example date. Replace with whatever date you want to convert. Once the date is converted to a Time instance, it can be serialized to BSON without any problem, as Time is a supported primitive type, that is to say, it can be saved using MongoMapper to the database.
As per EfratBlaier's comment I have updated the answer.
Date.today.to_time.utc

Why does this rails query behave differently depending on timezone?

I have a rails time-based query which has some odd timezone sensitive behaviour, even though as far as I know I'm using UTC. In a nutshell, these queries give different answers:
>> Model.find(:all,:conditions=>['created_at<=?',(Time.now-1.hours).gmtime]).length
=> 279
>> Model.find(:all,:conditions=>['created_at<=?',(Time.now-1.hours)]).length
=> 280
Where the DB actually does contain one model created in the last hour, and the total number of models is 280. So only the first query is correct.
However, in environment.rb I have:
config.time_zone = 'UTC'
The system time zone (as reported by 'date') is BST (which is GMT+1) - so somehow this winds up getting treated as UTC and breaking queries.
This is causing me all sorts of problems as I need to parameterise the query passing in different times to an action (which are then converted using Time.parse()), and even though I send in UTC times, this 'off by one hour' DST issue crops a lot. Even using '.gmtime()' doesn't always seem to fix it.
Obviously the difference is caused somehow by an implicit conversion somewhere resulting in BST being incorrectly treated as UTC, but why? Doesn't rails store the timestamps in UTC? Isn't the Time class timezone aware? I am using Rails 2.2.2
So what is going on here - and what is the safe way to program around it?
edit, some additional info to show what the DB and Time class are doing:
>> Model.find(:last).created_at
=> Tue, 11 Aug 2009 20:31:07 UTC +00:00
>> Time.now
=> Tue Aug 11 22:00:18 +0100 2009
>> Time.now.gmtime
=> Tue Aug 11 21:00:22 UTC 2009
The Time class isn't directly aware of your configured timezone. Rails 2.1 added a bunch of timezone support, but Time will still act upon your local timezone. This is why Time.now returns a BST time.
What you likely want is to interact with Time.zone. You can call methods on this like you would the Time class itself but it will return it in the specified time zone.
Time.zone.now # => Tue, 11 Aug 2009 21:31:45 UTC +00:00
Time.zone.parse("2:30 PM Aug 23, 2009") # => Sun, 23 Aug 2009 14:30:00 UTC +00:00
Another thing you have to be careful with is if you ever do queries on the database where you are comparing times, but sure to use the UTC time (even if you have a different time zone specified) because Rails always stores UTC in the database.
Item.all(:conditions => ["published_at <= ?", Time.now.utc])
Also, instead of Time.now-1.hour do 1.hour.ago. It is easier to read and Rails will automatically use the configured timezone.
The TimeZone you need to set is UK, this will automatically handle BST
Time.zone = 'UK'
Time.zone.now
=> Sun, 17 Oct 2010 02:09:54 BST +01:00
start_date_format = DateTime.strptime(#start_date, date_format)
start_date_format_with_hour =
DateTime.strptime((start_date_format.to_i + timezone_offset*60*60).to_s,'%s').strftime(date_format)
end_date_format = DateTime.strptime(#end_date, date_format)
end_date_format_with_hour = DateTime.strptime((end_date_format.to_i + timezone_offset*60*60).to_s,'%s').strftime(date_format)
#filters_date = "invoices.created_at >= ? AND invoices.created_at < ?", start_date_format_with_hour, end_date_format_with_hour

Resources