35.Ruby|strptime/strftime

strptime

「文字列」をDate._strptimeを用いて、Timeオブジェクトに変換。

require 'time'
Time.strptime('2001-02-03T04:05:06+09:00', '%Y-%m-%dT%H:%M:%S%z')
#=> 2001-02-03 06:05:06 +0900
require 'time'
Time.strptime('91/5/18 4:13:00', '%Y/%m/%d %T'){|y|
    if y > 100 then y
    elsif y >= 69 then y + 1900
    else y + 2000
    end
}
#=> 1991-05-18 04:13:00 +0900

docs.ruby-lang.org

strftime

「時刻」を「format 文字列」に従って文字列に変換した結果を返す。

p t = Time.new(2001,2,3,4,5,6,"+09:00")  # => 2001-02-03 04:05:06 +0900
p t.strftime("%m/%d/%Y")       # => "02/03/2001"
p t.strftime("%m/%-d/%_6Y")    # => "02/3/  2001"
p t.strftime("%I:%M%p")        # => "04:05AM"
p t.strftime("%I:%M%#p")       # => "04:05am"

docs.ruby-lang.org

注意

以下の場合はrequireをする必要はない。

p Time.now

以下の場合はrequire 'time'しないとエラーになる。

p Time.parse('2017-10-04 12:34:56')