20
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rubyでミリ秒、マイクロ秒単位のTimeを扱う

Posted at

ミリ秒を含む文字列に変換

  • Time#iso8601
  • TIme#xmlschema
require 'time'

time = Time.now
=> 2016-07-01 13:03:00 +0900

# マイクロ秒部分を整数で取得
time.usec
=> 193967

# iso8601フォーマットでマイクロ秒含めて表示
time.iso8601(6)
=> "2016-07-01T13:03:00.193967+09:00"

# 引数に小数点以下の桁数を入れるのでミリ秒なら3を指定する
irb(main):009:0> time.iso8601(3)
=> "2016-07-01T13:03:00.193+09:00"

# xmlschemaメソッドも同義
irb(main):010:0> time.xmlschema(3)
=> "2016-07-01T13:03:00.193+09:00"

文字列からTimeを生成

ISO8601フォーマットの文字列から生成する

  • Time.iso8601
  • Time.xmlschema

より多様なフォーマットに対応できる

  • Time.parse
time = Time.iso8601("2016-07-01T13:03:00.193967+09:00")
#=> 2016-07-01 13:03:00 +0900
time.usec
#=> 193967

time = Time.xmlschema("2016-07-01T13:08:56.629+09:00")
#=> 2016-07-01 13:08:56 +0900
time.usec
#=> 629000

time = Time.parse("2016-07-01T13:12:59.035692+09:00")
#=> 2016-07-01 13:12:59 +0900
time.usec
#=> 35692
20
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?