Skip to content

Instantly share code, notes, and snippets.

@masassiez
Created January 27, 2012 07:53
Show Gist options
  • Save masassiez/1687692 to your computer and use it in GitHub Desktop.
Save masassiez/1687692 to your computer and use it in GitHub Desktop.
Ruby1.8.7で前日のTimeオブジェクトを取得する
# ruby 1.8.7 only
# 前日のTimeオブジェクトを取得する
## パターン1:Timeクラスに Time#prev_day を追加
class Time
def next_day( n = 1, reset = true )
time = self + 60 * 60 * 24 * n
_hour, _min, _sec = reset ? [ 0, 0, 0 ] : [ hour, min, sec ]
Time.local( time.year, time.month, time.day, _hour, _min, _sec )
end
def prev_day( n = 1, reset = true )
time = self - 60 * 60 * 24 * n
_hour, _min, _sec = reset ? [ 0, 0, 0 ] : [ hour, min, sec ]
Time.local( time.year, time.month, time.day, _hour, _min, _sec )
end
end
p Time.now.prev_day
## パターン2:Dateオブジェクトに特異メソッド .to_time を追加
require "date"
yesterday = Date.today - 1
def yesterday.to_time
Time.local( year, mon, day )
end
p yesterday.to_time
## パターン3:Timeクラスから作成
yesterday = Time.now - 60 * 60 * 24 * 1
p Time.local( yesterday.year, yesterday.mon, yesterday.day )
## パターン4:Dateクラスから作成
require "date"
yesterday = Date.today - 1
p Time.local( yesterday.year, yesterday.mon, yesterday.day )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment