So my end goal is to have Heroku server's Time.now to be same as the time that you do new Date.now() from JavaScript. What I have done so far is catching the timezone offset from JavaScript, and set Time.zone on Rails with the appropriate client timezone, so now, Time.zone is the right time zone. But however, Time.now is still reflecting the real timezone instead of the one feeding into Time.zone. I guess that's not what I suppose to do at the first place.
So once again, all I want is, the server time to reflect the client time, so any operations such as Time.now or DateTime.now or Date.today will be shown with the client time.
You should apply the UTC offset when displaying the times.
All server-side time calculation or storage should be done in UTC.
Check this
1.8.7 :001 > Time.zone
=> #<ActiveSupport::TimeZone:0xb740d1b8 #tzinfo=#<TZInfo::TimezoneProxy: Etc/UTC>, #utc_offset=nil, #name="UTC", #current_period=nil>
1.8.7 :002 > Time.now
=> Fri Apr 20 13:13:53 +0530 2012
1.8.7 :003 > Time.zone.now
=> Fri, 20 Apr 2012 07:43:59 UTC +00:00
1.8.7 :004 > Time.zone = "Helsinki"
=> "Helsinki"
1.8.7 :005 > Time.zone
=> #<ActiveSupport::TimeZone:0xb70ab830 #tzinfo=#<TZInfo::TimezoneProxy: Europe/Helsinki>, #utc_offset=nil, #name="Helsinki", #current_period=nil>
1.8.7 :006 > Time.now
=> Fri Apr 20 13:14:48 +0530 2012
1.8.7 :007 > Time.zone.now
=> Fri, 20 Apr 2012 10:45:10 EEST +03:00
1.8.7 :008 > Time.zone.now.to_time.strftime("%c").to_datetime
=> Fri, 20 Apr 2012 10:47:01 +0000
1.8.7 :009 >
So Time.zone.now.to_time.strftime("%c").to_datetime will give you current time in user's timezone as UTC
Time.now always gives time in your server's timezone. Time.zone.now gives time in specified timezone.
Thanks,
Amit Patel
Related
How to avoid time zone correction?:
2.4.0 :077 > #purchase_lot[0]
=> #<Protocol44 publishDate: "2018-09-27 21:49:04">
2.4.0 :078 > #purchase_lot[0]['publishDate']
=> Fri, 28 Sep 2018 00:49:04 MSK +03:00
2.4.0 :079 > #purchase_lot[0]['publishDate'].class
=> ActiveSupport::TimeWithZone
The data come from the database (mariadb), the field type is DATETIME.
#purchase_lot[0]['publishDate'].utc
#=> 2018-09-27 21:49:04 UTC
Timestamps is usually stored in UTC
To stop conversion to default timezone you can use .utc method
#purchase_lot[0]['publishDate'].utc
I'm upgrading an big, old, clunky Rails application's Ruby (mostly so I don't have to re-install REE on my reformatted laptop) and I'm getting bitten pretty badly by timezone issues. Basically, pulling datetimes out of the database is not converting them to local time correctly:
New System - Ruby 2.1.2, Ubuntu 14.04
>> Time.zone.name
=> "Central Time (US & Canada)"
>> ActiveRecord::Base.time_zone_aware_attributes
=> true
>> ActiveRecord::Base.default_timezone
=> :utc
>> Transaction.last.created_at
=> 2014-07-15 02:09:02 UTC
>> Transaction.last.created_at_before_type_cast
=> 2014-07-15 02:09:02 UTC
>> Transaction.last.created_at.localtime
=> 2014-07-14 21:09:02 -0500
>> exit
$ date
Mon Jul 14 22:27:50 CDT 2014
Old System - REE, Ubuntu 12.04
>> Transaction.last.created_at
=> Mon, 14 Jul 2014 22:03:11 CDT -05:00
>> Transaction.last.created_at_before_type_cast
=> Tue Jul 15 03:03:11 UTC 2014
>> Transaction.last.created_at.localtime
=> Mon Jul 14 22:03:11 -0500 2014
As you can see, I've ensured that time_zone_aware_attributes is set, the zone is set (I set it in the environment.rb), and ActiveRecord is storing the times in UTC (as expected). I'm so stumped on this. Anyone have any ideas?
Update
before :all do
#current_tz = Time.zone
Time.zone = 'Pacific Time (US & Canada)'
end
after :all do
Time.zone = #current_tz
end
it 'should report time as Pacific time' do
shift = FactoryGirl.create(:shift)
new_obj = Transaction.create(shift: shift, time: DateTime.new(2013, 3, 31, 0, 0, 0, 0), amount: 0)
new_obj.reload
I18n.localize(new_obj.time, format: :timeonly).should_not == '12:00 am' #We created it with a UTC date, but it should get I18n'd to Pacific time
end
#en.yml
time:
formats:
timeonly: "%l:%M %p"
The above test is also failing. The I18n stuff seems totally broken.
Update 2
I seem to have isolated the problem to 1.9.3 -> 2.1. Using 1.9.3 is fine, I suppose, and I guess I'll just run that on the new server until I upgrade Rails. Sad. I'd still love to hear any suggestions about fixes.
Try using the I18n helpers to format/offset your time output - and force timezone (if needed)
puts I18n.localize(Transaction.last.created_at, format: :long)
Or
Time.use_zone("Central Time (US & Canada)") do
puts I18n.localize(Transaction.last.created_at, format: :long)
end
I recommend you set your default Time.zone to UTC as well and update it for each user explicitly as needed - here is a blog post that might be helpful: http://jessehouse.com/blog/2013/11/15/working-with-timezones-and-ruby-on-rails/
There is task model with attributes when and duration.
create_table "tasks", force: true do |t|
...
t.datetime "when"
t.integer "duration"
...
end
I wrote method for checking if task is active so I can show it on page.
This is active method:
def active?
if (self.when + self.duration) > Time.now
true
end
end
I tried in console to inspect object:
t.when + t.duration
=> Sun, 08 Sep 2013 01:01:00 UTC +00:00
DateTime.now
=> Sun, 08 Sep 2013 01:57:13 +0200
t.active?
=> true
It's true but I entered 1:00 time and 1 minute for duration and I hoped it shouldn't be true.
It seems that when column in database is not saved in correct time zone, so it gives incorrect results. How to solve this issue?
It seems that when column in database is not saved in correct time zone
1) Rails automatically converts times to UTC time before inserting them in the database (which is a good thing), which means the times have an offset of "+0000" . That means if you save a time of 8pm to the database, and your server is located in a timezone with an offset of "+0600", then the equivalent UTC time is 2pm, so 2pm gets saved in the database. In other words, your local server's time is 6 hours ahead of UTC time, which means that when it's 8pm in your server's time zone, it's 2pm in the UTC timezone.
2) When you compare dates, ruby takes the timezone offset into account--in other words ruby converts all times to the same timezone and then compares the times. Here is an example:
2.0.0p247 :086 > x = DateTime.strptime('28-01-2013 08:00:00 PM +6', '%d-%m-%Y %I:%M:%S %p %z')
=> Mon, 28 Jan 2013 20:00:00 +0600
2.0.0p247 :087 > y = DateTime.strptime('28-01-2013 08:20:00 PM +7', '%d-%m-%Y %I:%M:%S %p %z')
=> Mon, 28 Jan 2013 20:20:00 +0700
2.0.0p247 :088 > x < y
=> false
If you just compare the times of the two Datetime objects, x is less than y. However, y has a time of 8:20pm in a timezone that has an offset of +7, which is equivalent to the time 7:20pm in a timezone with an offset of +6. Therefore, y is actually less than x. You need to compare apples to apples, which means you need to mentally compare times that have been converted to the same timezone to get the same results as ruby/rails produces.
3) You can convert Time.now to a UTC time using the rails utc() method:
2.0.0p247 :089 > x = Time.now
=> 2013-09-07 8:00:00 +0600
2.0.0p247 :090 > x.utc
=> 2013-09-07 02:00:00 UTC
That's what ruby does before comparing Time.now to task.when + task.duration
4) You might find it more convenient to create a DateTime object with the time you want using:
DateTime.strptime('28-01-2013 08:00:00 PM +0', '%d-%m-%Y %I:%M:%S %p %z'
Because you are able to specify the offset as zero, you don't have to create a time that anticipates the conversion to UTC time.
Or you can use the change() method, which causes the offset() to change without converting the time:
2.0.0p247 :011 > x = DateTime.now
=> Sun, 08 Sep 2013 00:34:08 +0600
2.0.0p247 :012 > x.change offset: "+0000"
=> Sun, 08 Sep 2013 00:34:08 +0000
ActiveRecord stores timestamps in UTC by default. See How to change default timezone for Active Record in Rails? for changing default time zone.
You can also just use Time#in_time_zone to convert t.when to your timezone, see http://api.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html.
Here goes :
Time.zone.now => "Eastern Time (US & Canada)"
Time.zone.now => Wed, 15 Aug 2012 06:05:37 EDT -04:00
Time.zone.now + 39.years => Tue, 15 Aug 2051 06:06:03 EST -05:00
And so you have it, the end of our fabled Eastern Daylight Time has been prophesied by Ruby on Rails to end in the year 2051.
Also works for any other TimeZone changing area.
Time.zone
=> "Pacific Time (US & Canada)"
1.9.2p180 :003 > Time.zone.now
=> Wed, 15 Aug 2012 03:08:57 PDT -07:00
1.9.2p180 :004 > Time.zone.now + 39.years
=> Tue, 15 Aug 2051 03:08:57 PST -08:00
This exists in Rails 3.0 and in Rails 3.2.6
Yes, it looks like a bug. It's not Rails, however, it's the Ruby Time class. It has problems with times after 2038.
For example, with Ruby 1.8.7:
> Time.local(2037,8,16,9,30,15)
=> Sun Aug 16 09:30:15 -0400 2037
>
> Time.local(2038,8,16,9,30,15)
=> Mon Aug 16 09:30:15 -0500 2038
JRuby 1.6.7.2 - for instance - does not have this problem:
> Time.local(2038,8,16,9,30,15)
=> Mon Aug 16 09:30:15 -0400 2038
Note that, on MRI Ruby on 64-bit systems, the ActiveSupport time extension which supports the addition of durations ultimately calls Time.local or Time.utc via this method in active_support/core_ext/time/calculations.rb:
# Returns a new Time if requested year can be accommodated by Ruby's Time class
# (i.e., if year is within either 1970..2038 or 1902..2038, depending on system architecture);
# otherwise returns a DateTime
def time_with_datetime_fallback(utc_or_local, year, month=1, day=1, hour=0, min=0, sec=0, usec=0)
::Time.send(utc_or_local, year, month, day, hour, min, sec, usec)
rescue
offset = utc_or_local.to_sym == :local ? ::DateTime.local_offset : 0
::DateTime.civil(year, month, day, hour, min, sec, offset)
end
I guess the issue is that for years >= 2038, they were expecting an overflow exception and for DateTime to be used instead. On 64-bit systems, this doesn't happen.
UPDATE: This analysis is incorrect for Ruby 1.9.2+. Time.local works as expected, but the original problem still occurs.
I would expect Time and to_time to be reflective.
UPDATE
This is the answer, if you add the parameter :local, it doesn't ignore the offset. I find it wierd that it ignores data (the offset) by default, though...
Time.zone.now.to_s.to_time(:local) returns 2012-03-20 14:39:03 +0100
/UPDATE
> Time.zone.now.to_s
=> "2012-03-20 12:50:05 +0100"
> Time.zone.now.to_s.to_time.to_s
=> "2012-03-20 12:50:05 UTC"
# PROBLEM:
# UTC is +0000, meaning that there is 1 hour diff in the above
> Time.zone.now
=> Tue, 20 Mar 2012 12:51:32 CET +01:00
> Time.zone.now.to_time
=> Tue, 20 Mar 2012 12:51:32 CET +01:00
> Time.zone.now.to_json
=> "\"2012-03-20T12:50:36+01:00\""
> Time.zone.now.to_json.to_time
=> 2012-03-20 12:50:36 UTC
I have this problem with JSON messages. Anyway, I wouldn't expect to_time to actually change the time. OK to translate to UTC, probably, but it should adjust time accordingly. Anybody know if this is a known issue or "by design"?
This method, String#to_time, defined in ActiveSupport takes one parameter, form, which can be either :utc (default) or :local. So by default, it always returns a Time in UTC.
To get a Time with timezone:
Time.zone.parse("2012-03-20T12:50:36+01:00")