Help us understand the problem. What is going on with this article?

Rubyでミリ秒表記のUNIXTIMEを日付表記に変換する

More than 5 years have passed since last update.

timestampがms表記となっているものを、通常の時刻表記にRubyで変換したいときのTipsです。

ミリ秒は1000ミリ秒が1秒ですので、1000で割れば求められますね。
しかし整数演算とすると、ミリ秒が落ちてしまうため、1000.0で割ります。

$ pry
[1] pry(main)> time = 1412915400300
=> 1412915400300
[2] pry(main)> Time.at(time / 1000.0)
=> 2014-10-10 13:30:00 +0900

Time.at(time / 1000.0).strftime('%Y/%m/%d %H:%M:%S.%3N')
=> "2014/10/10 13:30:00.299"

任意のフォーマットで日時を求めるには次のコードが使えます。

$ pry
[1] pry(main)> time = 1412915400300
=> 1412915400300
[2] pry(main)> Time.at(time / 1000.0).strftime('%Y/%m/%d %H:%M:%S')
=> "2014/10/10 13:30:00"
[3] pry(main)> Time.at(time / 1000.0).strftime('%Y/%m/%d %H:%M:%S.%3N')
=> "2014/10/10 13:30:00.299"

参考情報
%N: 秒の小数点以下。桁の指定がない場合は9桁 (ナノ秒)、%6N: マイクロ秒 (6桁)、%3N: ミリ秒 (3桁)

先ほどのコードでミリ秒精度でのフォーマットを指定すると.300ではなくが.299が返るため、次のコードを用いると良いでしょう。

$ pry
[1] pry(main)> time = 1412915400300
=> 1412915400300
[2] pry(main)> Time.at(time / 1000.0).instance_eval { '%s.%03d' % [strftime('%Y/%m/%d %H:%M:%S'), (usec / 1000.0).round] }
=> "2014/10/10 13:30:00.300"

ref. http://d.hatena.ne.jp/tetsuyai/20101029/1288354522

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした