12
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 でエポックミリ秒

Last updated at Posted at 2017-03-24

JavaScript が Date.now() でエポックミリ秒を返すので時間のフォーマットをそれにしていたら、Ruby で扱うときに Time クラスだとマイクロ秒しか取れなくって非常に面倒くさかったので、Ruby でエポックミリ秒を生成する方法をいくつかまとめておく。

Time クラスを使う方法

Time.now.strftime('%s%L').to_i

%L でミリ秒単体で取れるので、エポック秒とくっつければエポックミリ秒になる

(Time.now.to_f * 1000).to_i

これだと文字列に変換しなくて済むけど、パッと見わかりづらい気もする

DateTime クラスを使う方法

require 'date'
DateTime.now.strftime('%Q').to_i

DateTime クラスだと %Q が使えるらしいが、 require 要るので微妙

12
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
12
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?