The last developer is using time in our app like this.
:timestamp_requested => Time.now.utc
I want to check if :timestamp_requested is between 4:15PM and 6:00PM CST.
I saw another post that uses in_time_zone but not sure how to check for between two times?
t = foo.start_time
#⇒ 2000-01-01 14:20:00 UTC
t.zone
#⇒ "UTC"
t.in_time_zone("America/Chicago")
#⇒ Sat, 01 Jan 2000 09:20:00 EST -05:00
You might want to try the use_zone method
Time.use_zone("America/Chicago") { (16..18).cover?(time.hour) && time.min >= 15 }
The easiest way to check the time is in the specific range would be to compare hours and minutes:
cst = time.in_time_zone("America/Guatemala") # CST whole year
(16..18).cover?(cst.hour) && cst.min >= 15
Related
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
Here is what I am trying to achieve - I have set up a scheduler to execute midnight of every friday, which collects the data from a service for the start date of last friday at 00:00:00 hrs and end time of last thursday at 23:59:59 hrs. Since it has to work every friday, I cannot hard code the dates so I thought of trying out DateTime.
So as per my requirement, if I am running the job on this Friday midnight i.e at "2014-12-12T03:00:00Z", then my start date should be "2014-12-05T00:00:00Z" and my end date should be "2014-12-11T23:59:59Z".
So to get start and end dates, I am trying to subtract days out of my now object. This is what I tried:
now = DateTime.now
p now.new_offset(0).to_s
startDate = now - 7
p startDate.new_offset(0).to_s
endDate = now - 1
p endDate.new_offset(0).to_s
This gives me the right date, but the time is wrong i.e. instead of start date with 00:00:00 and end date with 23:59:59 this would be start date with 03:00:00 and end date with 03:00:00.
How do I modify the DateTime object to get the start date with time at beginning of the day and end date with time at end of the day?
Sorry I am very bad in dealing with dates. Thanks in advance!!
You can use he beginning_of_day and end_of_day methods
1.9.3-p448 :001 > DateTime.now.beginning_of_day
=> Tue, 09 Dec 2014 00:00:00 +0300
1.9.3-p448 :002 > DateTime.now.end_of_day
=> Tue, 09 Dec 2014 23:59:59 +0300
I think what you are trying to do is easier done with the Date class :
require 'date'
start_date = (Date.today - 7).to_time
end_date = Date.today.to_time - 1
Instead of doing this manually, I will suggest a gem called Whenever: https://github.com/javan/whenever
It's a simple DSL for Ruby cron jobs.
Also remember that DateTime has beginning_of_day and end_of_day methods.
Just adding to the million questions about time zone and DST issues out there.
I have a form with separate date and time fields that I combine to create a DateTime like so
start_time = DateTime.parse("#{parse_date(form_date)} #{form_start_time} #{Time.zone}")
If I fill out my form with 21 Aug 2012 and 15:00, then these are the values that I see when I reload my form. If I then look at my start_time attribute in my model it is correctly set to Tue, 21 Aug 2012 15:00:00 EST +10:00.
The problem I am having occurs if I use a date later this year once daylight savings kicks in (I am in Australia). If I use 21 Dec 2012 and 15:00 then check start_time I see Fri, 21 Dec 2012 16:00:00 EST +11:00.
My interpretation of the problem is that the date is being saved in my current time zone (+10:00) as this is what I have told DateTime.parse to do. However when the value is returned, Rails is looking at the date and saying 'hey, it's daylight savings time in December' and returning the time in the +11:00 time zone.
What I want to do is tell DateTime.parse to save the time in the +11:00 time zone if DST is in effect. Clearly passing Time.zone into my string doesn't achieve this. Is there a simple way of doing this? I can see ways of doing it using Time#dst? but I suspect that this is going to create some really ugly convoluted code. I thought there might be a built in way that I'm missing.
(Answer for Rails 4.2.4, didn't check for older or newer versions)
Instead of using fixed shift +01:00, +02:00, etc, I recommend to use the in_time_zone String method with time zone name as argument :
Summer time :
ruby :001 > "2016-07-02 00:00:00".in_time_zone('Paris')
=> Sat, 02 Jul 2016 00:00:00 CEST +02:00
Winter time :
ruby :002 > "2016-11-02 00:00:00".in_time_zone('Paris')
=> Wed, 02 Nov 2016 00:00:00 CET +01:00
String#in_time_zone is the equivalent of :
ruby :003 > Time.find_zone!("Paris").parse("2016-07-02 00:00:00")
=> Sat, 02 Jul 2016 00:00:00 CEST +02:00
ruby :004 > Time.find_zone!("Paris").parse("2016-11-02 00:00:00")
=> Wed, 02 Nov 2016 00:00:00 CET +01:00
You can get the time zone names by :
$ rake time:zones:all
Or in rails console :
ruby :001 > ActiveSupport::TimeZone.all.map(&:name)
Or build collection for select tag :
ActiveSupport::TimeZone.all.map do |timezone|
formatted_offset = Time.now.in_time_zone(timezone.name).formatted_offset
[ "(GMT#{formatted_offset}) #{timezone.name}", timezone.name ]
end
And store the time zone name instead of the shift.
Note : don't confuse String#in_time_zone method and the Time#in_time_zone method.
consider the time zone for my system is 'Paris'.
ruby :001 > Time.parse("2016-07-02 00:00:00")
=> 2016-07-02 00:00:00 +0200
ruby :002 > Time.parse("2016-07-02 00:00:00").in_time_zone("Nuku'alofa")
=> Sat, 02 Jul 2016 11:00:00 TOT +13:00
Here's my solution so far. I'm hoping someone has a better one.
start_time = DateTime.parse "#{date} #{(form_start_time || start_time)} #{Time.zone}"
start_time = start_time - 1.hour if start_time.dst? && !Time.now.dst?
start_time = start_time + 1.hour if Time.now.dst? && start_time.dst?
It seems to work but I haven't rigorously tested it. I suspect it could be prettied up and shortened but I think this is readable and understandable. Any improvements?
I ran into this exact issue. My app allows users to see upcoming events. In the US we fall of DST on November 2nd and all events on and after that date were showing times an hour early.
We require the opportunity to have the timezone selected and stored to its own field. Before I was using the following to store my datetime:
timezone_offset = Time.now.in_time_zone(params[:opportunity][:time_zone]).strftime("%z") #-0700
DateTime.parse("#{params[:opportunity][:start_datetime]} #{timezone_offset}")
To fix the issue I have changed to:
start_datetime = Time.zone.parse(params[:opportunity][:start_datetime])
To display the correct times we use:
#opportunity.start_datetime.in_time_zone(#opportunity.time_zone)
I wouuld try and use
Australian Eastern Standard Time (AEST) (UTC +10).
Australian Central Standard Time (ACST) (UTC +9 ½).
Australian Western Standard Time (AWST) (UTC +8).
which adjust for Daylight Savings.
With Rails, we can use ActiveSupport::TimeZone for this:
tz = ActiveSupport::TimeZone.new 'Pacific Time (US & Canada)'
tz.parse(date_str_without_zone).to_datetime
I use TZip to get TimeZone strings (e.g. "Pacific Time (US & Canada)") from zip codes.
In case you have a custom date/time format, different than the supported by String#in_time_zone, you could also use (since rails 5) strptime like:
Time.find_zone!('Auckland').strptime('2021-02-02 08.00.00', '%Y-%m-%d %H.%M.%S')
If I have #today = Date.today.to_s, how do I convert #today into UTC (with the appropriate date only)?
Here I need is only date for example 2011-03-08 ie 08 March 2011. Please suggest something ?
Acutally I am looking for Yesterday date ??
You'll need to convert it to a Time object (or just use Time anyway) and then call Time#utc:
irb > Time.now
=> Tue Mar 08 15:32:36 +1100 2011
irb > Time.now.utc
=> Tue Mar 08 04:32:40 UTC 2011
You can then format it however you need it:
irb > #today = Time.now.utc
=> Tue Mar 08 04:34:25 UTC 2011
irb > #today.strftime("%Y-%m-%d")
=> "2011-03-08"
If you want to convert #today into UTC.
Then try this
>> #today = Date.today.to_s
>> DateTime.parse(#today)
Try
1.day.ago.utc
or
1.day.ago.utc.strftime('%b %B, %Y')
The format below should give you the date format of Yesterday which you are looking for formatted as 07 March, 2011. Look into the ruby Time class manual for more information on strftime time formating function. Good luck!
I strongly recommend you to move towards time zones in rails. Its easier and lot more convenient to work with than Time.now. You should be able to set the time zone in environment.rb with config.time_zone = "Chennai" or your time zone. After doing this, you should be able to get the time with UTC information by Doing Time.zone.now. To find the UTC offset, you could type Time.zone.
> e = Event.first
> e.registration_start_utc #registration_start_utc is a datetime column
=> Sat, 23 Oct 2010 06:38:00 UTC +00:00
> e.registration_start_utc.utc?
=> true
> ActiveSupport::TimeZone.find_tzinfo("America/New_York").utc_to_local(e.registration_start_utc)
=> Sat, 23 Oct 2010 02:38:00 UTC +00:00
2 questions about this:
1) Why is that last output showing "UTC" -- the hour got converted (6 => 2) but it still says UTC. Why not EST/EDT?
2) What happens after daylight savings time switches over and the offset for New York moves from -4 to -5? The value in the DB doesn't change so my only conclusion is that my app will start showing "1:38" everywhere instead of the correct 2:38?
I'm mostly concerned with #2 here. #1 is more of a curiosity.
Thanks!
2) utc_to_local uses the date to determine which offset is correct, so the output will always be the same for a given date.
You can test for that like this:
t = Time.utc(2011,3, 14, 12)
# => 2011-03-14 12:00:00 UTC
t2 = Time.utc(2011,3, 11, 12)
# => 2011-03-11 12:00:00 UTC
ActiveSupport::TimeZone.find_tzinfo("America/New_York").utc_to_local(t)
# => 2011-03-14 08:00:00 UTC
ActiveSupport::TimeZone.find_tzinfo("America/New_York").utc_to_local(t2)
# => 2011-03-14 07:00:00 UTC
1) It doesn't seem right to me either. My guess is that they are interested only in the actual value of the hour, minutes, etc... and disregard the timezone.
In any case, you might be better off using:
e.registration_start_utc.in_time_zone("Eastern Time (US & Canada)")
See also this question I just asked...