日付の加算・減算
Rubyで日付や日時の加算または減算する方法。フォーマット同様にこちらもよく調べます。なので、日付関連の操作ってなんでもいいので統一してくれないものか...とか思ったりします。
Rubyの場合、active_supportを利用するのが簡単です。
active_supportのインストール
gem install activesupport
コード
require 'active_support'
require 'active_support/core_ext'
def format_date(dt)
return dt.strftime("%Y-%m-%d %H:%M:%S")
end
dt = Time.now
puts format_date(dt) # 2017-03-24 21:19:24
puts "[S] " + format_date(dt - 1.second) # [S] 2017-03-24 21:19:23
puts "[M] " + format_date(dt - 1.minute) # [M] 2017-03-24 21:18:24
puts "[H] " + format_date(dt - 1.hour) # [H] 2017-03-24 20:19:24
puts "[d] " + format_date(dt - 1.day) # [d] 2017-03-23 21:19:24
puts "[w] " + format_date(dt - 1.week) # [w] 2017-03-17 21:19:24
puts "[m] " + format_date(dt - 1.month) # [m] 2017-02-24 21:19:24
puts "[Y] " + format_date(dt - 1.year) # [Y] 2016-03-24 21:19:24