ROR + TodayDate in UTC Format - ruby-on-rails

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.

Related

Daylight Saving Time start and end dates in Ruby/Rails

I'm working on a Rails app where I need to find the Daylight Saving Time start and end dates given a specific offset or timezone.
I basically save in my database the timezone offset received from a user's browser( "+3", "-5") and I want to modify it when it changes because of daylight saving time.
I know Time instance variables have the dst? and isdst methods which return true or false if the date stored in them is in the daylight saving time or not.
> Time.new.isdst
=> true
But using this to find the Daylight Saving Time beginning and end dates would take too many resources and I also have to do it for each timezone offset I have.
I would like to know a better way of doing this.
Ok, building on what you've said and #dhouty's answer:
You want to be able to feed in an offset and get a set of dates for knowing if there is a DST offset or not. I would recommend ending up with a range made of two DateTime objects, as that is easily used for many purposes in Rails...
require 'tzinfo'
def make_dst_range(offset)
if dst_end = ActiveSupport::TimeZone[offset].tzinfo.current_period.local_end
dst_start = ActiveSupport::TimeZone[offset].tzinfo.current_period.local_start
dst_range = dst_start..dst_end
else
dst_range = nil
end
end
Now you have a method that can do more than just take an offset thanks to the sugar that comes with ActiveSupport. You can do things like:
make_dst_range(-8)
#=> Sun, 08 Mar 2015 03:00:00 +0000..Sun, 01 Nov 2015 02:00:00 +0000
make_dst_range('America/Detroit')
#=> Sun, 08 Mar 2015 03:00:00 +0000..Sun, 01 Nov 2015 02:00:00 +0000
make_dst_range('America/Phoenix')
#=> nil #returns nil because Phoenix does not observe DST
my_range = make_dst_range(-8)
#=> Sun, 08 Mar 2015 03:00:00 +0000..Sun, 01 Nov 2015 02:00:00 +0000
Today happens to be August 29th so:
my_range.cover?(Date.today)
#=> true
my_range.cover?(Date.today + 70)
#=> false
my_range.first
#=> Sun, 08 Mar 2015 03:00:00 +0000
#note that this is a DateTime object. If you want to print it use:
my_range.first.to_s
#=> "2015-03-08T03:00:00+00:00"
my_range.last.to_s
#=> "2015-11-01T02:00:00+00:00"
ActiveSupport gives you all sorts of goodies for display:
my_range.first.to_formatted_s(:short)
#=> "08 Mar 03:00"
my_range.first.to_formatted_s(:long)
#=> "March 08, 2015 03:00"
my_range.first.strftime('%B %d %Y')
#=> "March 08 2015"
As you can see it's completely doable with just the offset, but as I said, offset doesn't tell you everything, so you might want to grab their actual time zone and store that as a string since the method will happily accept that string and still give you the date range. Even if you are just getting the time offset between your zone and theirs, you can easily figure correct that to the UTC offset:
my_offset = -8
their_offset = -3
utc_offset = my_offset + their_offset
What you are probably looking for is TZInfo::TimezonePeriod. Specifically, the methods local_start/utc_start and local_end/utc_end.
Given a timezone offset, you can get a TZInfo::TimezonePeriod object with
ActiveSupport::TimeZone[-8].tzinfo.current_period
Or if you have a timezone name, you can also get a TZInfo::TimezonePeriod object with
ActiveSupport::TimeZone['America/Los_Angeles'].tzinfo.current_period

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

Correcting time for daylight savings in rails DateTime.parse

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')

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

Rails custom TimeZone

How can I set my rails application with custom timezone? I want to set my application timezone with UTC-04:00 without daylight saving.
update: To clarify my question, I understand that I can set the time zone name in the environment.rb file with one of the names from TimeZone constants. I want my application timezone as UTC -04:00 without daylight saving.
Thanks,
Soe Moe
Suppose you want a timezone that does NOT use DST, and basically tracks Eastern Standard Time always (also known as Eastern Prevailing Time). You want it to be a -05:00 offset always.
Use the Timezone Etc/GMT+5. Rails will lazy-load timezones not in its normal list from TZInfo, so you can cherry pick from: http://tzinfo.rubyforge.org/svn/trunk/tzinfo/lib/tzinfo/definitions/Etc/
Here are some examples to prove this, in my Rails 3.2 rails console:
Daylight Savings example. October 4 is daylight savings time. You would expect your hours to be off by one for Eastern time and your special timezone. 2011-10-05 04:57:23 in UTC should be 2011-10-05 00:57:23 Eastern Daylight Time.
1.9.3p0 :014 > DateTime.civil(2011,10,5,4,57,23)
=> Wed, 05 Oct 2011 04:57:23 +0000
1.9.3p0 :015 > DateTime.civil(2011,10,5,4,57,23).in_time_zone('Eastern Time (US & Canada)')
=> Wed, 05 Oct 2011 00:57:23 EDT -04:00
1.9.3p0 :016 > DateTime.civil(2011,10,5,4,57,23).in_time_zone('Etc/GMT+5')
=> Tue, 04 Oct 2011 23:57:23 GMT+5 -05:00
Non-Daylight Savings example. December 1 is standard time. You would expect Eastern time and your custom "always EST" to be equivalent. 2011-12-01 02:30:45 should be 2011-11-30 21:30:45 in both EST and your special timezone.
1.9.3p0 :010 > DateTime.civil(2011,12,1,2,30,45)
=> Thu, 01 Dec 2011 02:30:45 +0000
1.9.3p0 :012 > DateTime.civil(2011,12,1,2,30,45).in_time_zone('Eastern Time (US & Canada)')
=> Wed, 30 Nov 2011 21:30:45 EST -05:00
1.9.3p0 :013 > DateTime.civil(2011,12,1,2,30,45).in_time_zone('Etc/GMT+5')
=> Wed, 30 Nov 2011 21:30:45 GMT+5 -05:00
Why is it GMT+5 and not GMT-5? I'm not entirely sure. I would have expected it to be GMT-5, but this is how the etc timezones seem to work in TZInfo.
Normally you'd only want to do this when the location you live in doesn't practice Daylight Savings Time. In your particular case, you're in luck, and can use the "La Paz" timezone. According to this website, it doesn't practice DST.
You can always run rake time:zones:all and see what UTC offsets correspond to the offset you're interested in using. Then google those offsets to see if they change during the year.
I don't know of a general method to tell Rails you want UTC +/- a fixed offset.

Resources