Date Operation in Ruby
- Last modified atOne of my favorite features in Ruby is date operation. Here are examples date operation in Ruby on Rails and Ruby’s Standard Library.
Date Operation in Ruby on Rails and Active Record.
# Rails 5.1
# rails console
now = Date.today
# => Sun, 22 Jul 2018
one_week_ago_datetime = 1.week.ago
# => Sun, 15 Jul 2018 13:18:02 UTC +00:00
one_week_ago = one_week_ago_datetime.to_date
# => Sun, 15 Jul 2018
one_day_from_now = 1.day.from_now
# => Mon, 23 Jul 2018 13:18:09 UTC +00:00
two_days_ago = now - 2
# => Fri, 20 Jul 2018
two_years_ago = now - 2.years
# => Fri, 22 Jul 2016
date_range = (one_week_ago.to_date..now)
# => Sun, 15 Jul 2018..Sun, 22 Jul 2018
total_days = date_range.count
# => 8
total_days = (now - one_week_ago.to_date).to_i + 1
# => 8
# Active Record query examples
Post.where('created_at >= ?', one_week_ago)
Post.where('created_at < ?', one_day_from_now)
Post.where('created_at > ?', two_years_ago)
Post.where(created_at: now)
# data range
Post.where('created_at BETWEEN ? AND ?', one_week_ago, now)
Post.where(created_at: date_range)
Date Operation with Ruby’s Standard Library and Sequel
# Ruby 2.5.1
# irb
require 'date'
now = Date.today
# => #<Date: 2018-07-22 ((2458322j,0s,0n),+0s,2299161j)>
one_week_ago = now - 7
# => #<Date: 2018-07-15 ((2458315j,0s,0n),+0s,2299161j)>
one_day_from_now = now + 1
# => #<Date: 2018-07-23 ((2458323j,0s,0n),+0s,2299161j)>
two_days_ago = now - 2
# => #<Date: 2018-07-20 ((2458320j,0s,0n),+0s,2299161j)>
two_years_ago = now.prev_year(2)
# => #<Date: 2016-07-22 ((2457592j,0s,0n),+0s,2299161j)>
date_range = (one_week_ago..now)
# => #<Date: 2018-07-15 ((2458315j,0s,0n),+0s,2299161j)>..#<Date: 2018-07-22 ((2458322j,0s,0n),+0s,2299161j)>
total_days = date_range.count
# => 8
total_days = (now - one_week_ago).to_i + 1
# => 8
# Sequel query examples
# http://sequel.jeremyevans.net
Post.where{created_at >= one_week_ago}
Post.where{created_at < one_day_from_now}
Post.where{created_at > two_years_ago}
Post.where{created_at =~ now} # => WHERE (created_at = '2018-07-22')
# date range
Post.where{created_at >= one_week_ago}.where{created_at <= now}
# => #<Sequel::Postgres::Dataset: "SELECT * FROM \"posts\" WHERE ((\"created_at\" >= '2018-07-15') AND (\"created_at\" <= '2018-07-22'))">
Post.where(created_at: date_range)
# => #<Sequel::Postgres::Dataset: "SELECT * FROM \"posts\" WHERE ((\"created_at\" >= '2018-07-15') AND (\"created_at\" <= '2018-07-22'))">
Sponsored Links
- Register to Digital Ocean cloud with this link and get $200 credit
- Looking for cheap CDN? Bunny is the answer
- Alternative Cloud besides AWS and Digital Ocean