LoginSignup
19
21

More than 5 years have passed since last update.

[Ruby] 数値・日付時間のformat

Last updated at Posted at 2017-04-20

数値

roundは四捨五入されて表示される。

1.234567.round    # => 1  (Fixnum)
1.234567.round(2) # => 1.23  (Float)
1.234567.round(3) # => 1.235  (Float)

sprintfを使うと、0埋めでの表示となる。

sprintf("%.2f", 1.234) # => "1.23"
sprintf("%.3f", 1.234) # => "1.234"
sprintf("%.6f", 1.234) # => "1.234000"

# %dにすると
sprintf("%.6d", 1.234) # => "000001"

# 他の書き方
format('%.6f', 1.234)  # => "1.234000"
puts '%.6f' % 1.234     # =  "1.234000"

日付時間

time = Time.new(2017, 1, 1, 12, 30, 45)
time.strftime("%Y年 %m月 %d日") # => "2017年 01月 01日"
time.strftime("%Y年 %m月 %d日, %H:%M:%S") # => "2017年 01月 01日, 12:30:45"

よく使うもの(個人的まとめ)

フォーマット文字列 出力形式
%A 曜日の名称(Sunday, Monday, ...)
%a 曜日の省略名(Sun, Mon, ...)
%B 月の名称(January, February, ...)
%b 月の省略名(Jan, Feb, ...)
%d 日(01-31)
%H 24時間制の時(00-23)
%I 12時間制の時(01-12)
%M 分(00-59)
%S 秒(00-60) (60はうるう秒)
%Y 西暦を表す数
%y 西暦の下2桁(00-99)
%p 午前または午後(AM,PM)

あんまり使わない

フォーマット文字列 出力形式
%c 日付と時刻("Sun Jan 1 12:30:45 2017")
%X 時刻("12:30:45")
%x 日時("01/01/17")
%m 月を表す数字(01-12)
%j 年中の通算日(001-366)
%U 週を表す数。最初の日曜日が第1週の始まり(00-53)
%W 週を表す数。最初の月曜日が第1週の始まり(00-53)
%w 曜日を表す数。日曜日が0(0-6)
%Z タイムゾーン("JST", ...)
%% パーセント文字

参考リンク

http://railsdoc.com/references/strftime
http://qiita.com/tksmaru/items/0f9283d0c5f0ee716f2f

19
21
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
19
21