Created
September 27, 2017 11:44
-
-
Save Peranikov/7e9849d4cfeebe9bada9bd507930621f to your computer and use it in GitHub Desktop.
5-6 Time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Time.now # => 2017-09-27 19:59:10 +0900 | |
Time.new # => 2017-09-27 19:59:10 +0900 | |
# タイムゾーンを得る | |
Time.now.zone # => "JST" | |
# UTC時間を得る | |
Time.now.getutc # => 2017-09-27 11:00:01 UTC | |
# タイムゾーンをUTCに変更する | |
now = Time.now | |
now.utc | |
now.zone # => "UTC" | |
# UNIXエポックからの経過秒数を得る | |
now = Time.now | |
now.to_i # => 1506510228 | |
now.to_f # => 1506510228.984828 | |
now.to_r # => (376627557246207/250000) | |
# 文字列で得る | |
now.to_r # => "2017-09-27 20:03:48 +0900" | |
# 5-6-2 比較 | |
# 1秒以下の時間も保持しているため == で比較してもtrueになるとは限らない | |
a = Time.now; b = Time.now # => 2017-09-27 20:06:39 +0900 | |
a == b # => false | |
a.nsec # => 744499000 | |
b.nsec # => 744500000 | |
# TimeはComparableモジュールをincludeしているので比較することが可能 | |
past = Time.now | |
sleep 1 | |
future = Time.now | |
past <=> future # => -1 | |
past < future # => true | |
past <= future # => true | |
past > future # => false | |
past >= future # => false | |
# 5-6-3 加算/減算 | |
# 右辺は秒数として扱われる | |
now = Time.now # => 2017-09-27 20:12:11 +0900 | |
now + 1 # => 2017-09-27 20:12:12 +0900 | |
now - 1 # => 2017-09-27 20:12:10 +0900 | |
a = Time.now; sleep 1; b = Time.now | |
a - b # => 1.00858 | |
# 5-6-4 Timeオブジェクトの生成 | |
Time.at(0) # UNIXエポックを取得 | |
Time.at(0).getutc # UTCとして取得 | |
# UTCを得る | |
Time.utc(2011, 4, 1, 5, 30, 20, 100) # => 2011-04-01 05:30:20 UTC | |
Time.utc(2011) # => 2011-01-01 00:00:00 UTC | |
# 地方時を得る | |
Time.local(2011, 4, 1, 5, 30, 20, 100) # => 2011-04-01 05:30:20 UTC +9000 | |
Time.local(2011) # => 2011-01-01 00:00:00 +9000 | |
# 配列で秒、分、時、日、月、年、曜日(0-6)、その年の通算日、夏時間か、タイムゾーンを得る | |
args = Time.now.to_a # => [38, 37, 20, 27, 9, 2017, 3, 270, false, "JST"] | |
# 配列からTimeオブジェクトを得る | |
Time.utc(*args) # => 2017-09-27 20:37:38 UTC | |
Time.local(*args) # => 2017-09-27 20:37:38 +0900 | |
# 5-6-5 文字列表現 | |
# strftimeで任意のフォーマットにできる | |
now = Time.now | |
now.strftime('%Y/%m/%d %H:%M:%S') # => "2017/09/27 20:24:05" | |
now = Time.now # => 2017-09-27 20:39:33 +0900 | |
now.strftime('%Y') # => "2017" | |
now.strftime('010%Y') # => "0000002017" | |
# _ で0埋めではなく空白埋めにする | |
now.strftime('%m') # => "01" | |
now.strftime('%-m') # => "1" | |
# #で大文字であれば小文字、小文字であれば大文字にする | |
now.strftime('%#p') # => "pm" | |
now.strftime('%#P') # => "PM" | |
# ^で大文字にする | |
now.strftime('%B') # => "September" | |
now.strftime('%^B') # => "SEPTEMBER" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment