Working with date and time - ruby-on-rails

I have a UTC date of Tue, 16 Feb 2010 03:12:02 UTC +00:00, for example.
I want to add 168 hours to this date to get a future UTC date.
What's the best way to do that?

You tagged the question rails so here is how you can do this in Rails, using some of the helpers:
time_string = 'Tue, 16 Feb 2010 03:12:02 UTC +00:00'
new_time = Time.parse( time_string ) + 168.hours
If you already have it as a Time object, just add the 168.hours:
new_time = old_time + 168.hours
Or you can just add 1.week:
new_time = old_time + 1.week

FYI, '9.days' is more simpler than '168.hours'.
>> new_time = Time.parse( time_string ) + 168.hours
=> Tue Feb 23 03:12:02 UTC 2010
>> new_time = Time.parse( time_string ) + 9.days
=> Thu Feb 25 03:12:02 UTC 2010

In vanilla Ruby it's not much more difficult:
time_string = 'Tue, 16 Feb 2010 03:12:02 UTC +00:00'
new_time = DateTime.parse( time_string ) + 7
(You could just use the Date class, it would still work.)
I admit adding in hours is a little more tricky.

Related

Get the difference in days between two dates Rails "Date"

What is the proper way to subtract or add dates in Rails?
I tried the intuitive way but got Rational:
irb(main):089:0> Date.today.increase_by("3 days")
=> Sun, 19 May 2019
irb(main):090:0> Date.today
=> Thu, 16 May 2019
irb(main):091:0> Date.today.increase_by("3 days") - Date.today
=> (3/1)
Disclaimer: Please note that I am new to Ruby and Rails as well. 2 months of experience so far :)
You can use
Date.today # Thu, 16 May 2019
Date.today + 3 # Thu, 19 May 2019
Date.today - 3 # Thu, 13 May 2019
For Difference
Date.today + 3 # Thu, 19 May 2019
Date.today - 3 # Thu, 13 May 2019
(d1 - d2).to_i # 6 (Days)

Finding days between 2 days in Ruby on Rails

I am facing some problem in finding the days between 2 dates.
The scenario is as follow :
time = Time.new
enddate_timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
startdate = #logInfo.updated_at #here updated_at is the column in the db .
What is the best way to find the days ?
Post.where(["date(created_at) BETWEEN ? AND ?", Date.yesterday, Date.tomorrow]
More details: http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-where
There are several possible solutions. A possibility is to create a Range with the dates, then convert the range into an array
# set the boundaries
today = Time.current
past = 5.days.ago
Note that both boundaries are time instances. We should cast them into dates. I used time(s) because your column is a time.
range = past.to_date..today.to_date
# => Sun, 29 Dec 2013..Fri, 03 Jan 2014
Use to_a to expand the range getting all the days
range.to_a
# => [Sun, 29 Dec 2013, Mon, 30 Dec 2013, Tue, 31 Dec 2013, Wed, 01 Jan 2014, Thu, 02 Jan 2014, Fri, 03 Jan 2014]
range.count
# => 6
You can also enumerate them
range.each { |day| puts day.day }
29
30
31
1
2
3
now = Time.now
future = Time.now + 100 days
while now < future
now = now + 1.day
puts now
end
This will give you the dates, not the days count.
(startdate.beginning_of_day..enddate_timestamp.to_time.beginning_of_day).step(1.day) do |day|
puts day
end
P.S: Performance wise it's not good.

Ruby: Convert BST time to UTC

script/console
>> t = Time.at(1158609371)
=> Mon Sep 18 20:56:11 +0100 2006
>> t.zone
=> "BST"
>> s = Shop.find(:first)
>> s.creation_tsz = t.utc
=> Mon Sep 18 19:56:11 UTC 2006
>> s.creation_tsz.zone
=> "UTC"
>> s.save
>> s = Shop.find(:first)
>> s.creation_tsz
=> Sat Jan 01 19:56:11 UTC 2000
How come it changed from Sep 18 2006 to Jan 01 2000? Timezone is setup to use "UTC" in environment.rb. And just so you are aware I have tried numerous variations of line s.creation_tsz = t.utc . All with failure.
Is it possible that in the database, s.creation_tsz stores only a time, but not a date part, for example a MySQL TIME type, as opposed to the TIMESTAMP or DATETIME type.

"Ago" date/time functions in Ruby/Rails

I was wondering if there's a way in Rails to calculate time stamp like - half a minute ago, 2 minute ago, 1 day ago etc. Something like twitter real time date stamp.
I want to know if Ruby/Rails has a built-in function for such date-time conversion?
You can use:
10.minutes.ago
2.days.since
Or in your views you have the helpers:
distance_of_time_in_words(from_time, to_time)
time_ago_in_words(from_time)
Check the API for details and more options.
You can use available methods to get the time in past or future using ago, since alias for from_now and many available methods
Time.current
#=> Tue, 20 Sep 2016 15:03:30 UTC +00:00
2.minutes.ago
#=> Tue, 20 Sep 2016 15:01:30 UTC +00:00
2.minutes.since
#=> Tue, 20 Sep 2016 15:05:30 UTC +00:00
1.month.ago
#=> Sat, 20 Aug 2016 15:03:30 UTC +00:00
1.year.since
#=> Wed, 20 Sep 2017 15:03:30 UTC +00:00
Check all the available methods in Time class
distance_of_time_in_words:
from_time = Time.now
distance_of_time_in_words(from_time, from_time + 50.minutes) # => about 1 hour
distance_of_time_in_words(from_time, 50.minutes.from_now) # => about 1 hour
distance_of_time_in_words(from_time, from_time + 15.seconds) # => less than a minute
distance_of_time_in_words(from_time, from_time + 15.seconds, include_seconds: true) # => less than 20 seconds
time_ago_in_words:
time_ago_in_words(3.minutes.from_now) # => 3 minutes
time_ago_in_words(3.minutes.ago) # => 3 minutes
time_ago_in_words(Time.now - 15.hours) # => about 15 hours

Rails ActiveSupport Time Parsing?

Rails' ActiveSupport module extends the builtin ruby Time class with a number of methods.
Notably, there is the to_formatted_s method, which lets you write Time.now.to_formatted_s(:db) to get a string in Database format, rather than having to write ugly strftime format-strings everywhere.
My question is, is there a way to go backwards?
Something like Time.parse_formatted_s(:db) which would parse a string in Database format, returning a new Time object. This seems like something that rails should be providing, but if it is, I can't find it.
Am I just not able to find it, or do I need to write it myself?
Thanks
It looks like ActiveSupport does provide the parsing methods you are looking for (and I was looking for too), after all! — at least if the string you are trying to parse is a standard, ISO-8601-formatted (:db format) date.
If the date you're trying to parse is already in your local time zone, it's really easy!
> Time.zone.parse('2009-09-24 08:28:43')
=> Thu, 24 Sep 2009 08:28:43 PDT -07:00
> Time.zone.parse('2009-09-24 08:28:43').class
=> ActiveSupport::TimeWithZone
and that time-zone-aware time can then easily be converted to UTC
> Time.zone.parse('2009-09-24 08:28:43').utc
=> 2009-09-24 15:28:43 UTC
or to other time zones:
> ActiveSupport::TimeZone.us_zones.map(&:name)
=> ["Hawaii", "Alaska", "Pacific Time (US & Canada)", "Arizona", "Mountain Time (US & Canada)", "Central Time (US & Canada)", "Eastern Time (US & Canada)", "Indiana (East)"]
> Time.zone.parse('2009-09-24 08:28:43').utc.in_time_zone('Eastern Time (US & Canada)')
=> Thu, 24 Sep 2009 11:28:43 EDT -04:00
If the date string you're trying to parse is in UTC, on the other hand, it doesn't look like there's any method to parse it directly into a TimeWithZone, but I was able to work around that be first using DateTime.strptime...
If the date you're trying to parse is in UTC and you want it to stay as UTC, you can use:
> DateTime.strptime('2009-09-24 08:28:43', '%Y-%m-%d %H:%M:%S').to_time
=> 2009-09-24 08:28:43 UTC
If the date you're trying to parse is in UTC and you want it converted to your default time zone, you can use:
> DateTime.strptime('2009-09-24 08:28:43', '%Y-%m-%d %H:%M:%S').to_time.in_time_zone
=> Thu, 24 Sep 2009 01:28:43 PDT -07:00
It looks like it can even parse other formats, such as the strange format that Time#to_s produces:
irb -> Time.zone.parse('Wed, 23 Sep 2009 02:18:08').to_s(:db)
=> "2009-09-23 09:18:08"
irb -> Time.zone.parse('Wed, 23 Sep 2009 02:18:08 EDT').to_s(:db)
=> "2009-09-23 06:18:08"
I'm quite impressed.
Here are some more examples from [http://api.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html][1]:
Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)'
Time.zone.local(2007, 2, 10, 15, 30, 45) # => Sat, 10 Feb 2007 15:30:45 EST -05:00
Time.zone.parse('2007-02-10 15:30:45') # => Sat, 10 Feb 2007 15:30:45 EST -05:00
Time.zone.at(1170361845) # => Sat, 10 Feb 2007 15:30:45 EST -05:00
Time.zone.now # => Sun, 18 May 2008 13:07:55 EDT -04:00
Time.utc(2007, 2, 10, 20, 30, 45).in_time_zone # => Sat, 10 Feb 2007 15:30:45 EST -05:00
More documentation links for reference:
http://api.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html
http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html
ActiveSupport::TimeZone.new('UTC').parse('2009-09-23 09:18:08')
=> Wed, 23 Sep 2009 09:18:08 UTC +00:00
Rails 5 finally provides strptime!
value = '1999-12-31 14:00:00'
format = '%Y-%m-%d %H:%M:%S'
Time.zone.strptime(value, format)
# => Fri, 31 Dec 1999 14:00:00 HST -10:00
ActiveSupport::TimeZone.all.sample.strptime(value, format)
# => Fri, 31 Dec 1999 14:00:00 GST +04:00
I just ran into this as well and none of the above answers were satisfactory to me. Ideally one could use ActiveSupport::TimeZone just like Time and call .strptime on it with any arbitrary format and get back the correct TimeZone object. ActiveSupport::TimeZone.strptime doesn't exist so I created this monkeypatch:
class ActiveSupport::TimeZone
def strptime(str, fmt, now = self.now)
date_parts = Date._strptime(str, fmt)
return if date_parts.blank?
time = Time.strptime(str, fmt, now) rescue DateTime.strptime(str, fmt, now)
if date_parts[:offset].nil?
ActiveSupport::TimeWithZone.new(nil, self, time)
else
time.in_time_zone(self)
end
end
end
>> "2009-09-24".to_date
=> Thu, 24 Sep 2009
>> "9/24/2009".to_date
=> Thu, 24 Sep 2009
Works great unless your date is in some weird format.

Resources