LoginSignup
0
3

More than 5 years have passed since last update.

個人的にRubyのstrftimeでよく使う表記

Posted at

目的

  • rubyの時刻表記を任意のフォーマットに整形してくれるメソッドであるstrftime
  • 使い方はとても簡単だけど、忘れる
    • たとえば%mと%Mのどちらが月なのか?分なのか?とか
  • %の表記を覚えるのもいいけど、使うフォーマットはいつも同じ
  • よく使うフォーマットと表記の対応を羅列して、コピペで使えるようにしたほうが便利かと思ったのでメモとして作成した

環境

ruby 2.3.1

コード

まず時刻を取得

> t = Time.now
=> 2017-01-06 09:54:49 +0900

年月日

## 半角数字のみ
> t.strftime('%Y%m%d')
=> "20170106"

## 半角スラッシュ(/)区切り
> t.strftime('%Y/%m/%d')
=> "2017/01/06"

## 全角 年 月 日 区切り
> t.strftime('%Y年%m月%d日')
=> "2017年01月06日"

年月日時分

## 半角数字のみ
> t.strftime('%Y%m%d%H%M')
=> "201701060954"

## 半角スラッシュ(/)区切りと半角スペースと半角コロン(:)区切り
> t.strftime('%Y/%m/%d %H:%M')
=> "2017/01/06 09:54"

## 全角 年 月 日 時 分区切り(24時間表記)
> t.strftime('%Y年%m月%d日%H時%M分')
=> "2017年01月06日09時54分"

## 全角 年 月 日 時 分区切り(12時間表記)
> t.strftime('%Y年%m月%d日%I時%M分%p')
=> "2017年01月06日09時54分AM"

年月日時分秒

## 半角数字のみ
> t.strftime('%Y%m%d%H%M%S')
=> "20170106095449"

## 全角 年 月 日 時 分 秒区切り(24時間表記)
> t.strftime('%Y年%m月%d日%H時%M分%S秒')
=> "2017年01月06日09時54分49秒"

0を除いた表記

  • % の後に - を挿入する
## 年月日
> t.strftime('%Y年%-m月%-d日')
=> "2017年1月6日"

## 年月日時分
> t.strftime('%Y年%-m月%-d日%-H時%-M分%')
=> "2017年1月6日9時54分%"

## 年月日時分秒
> t.strftime('%Y年%-m月%-d日%-H時%-M分%-S秒')
=> "2017年1月6日9時54分49秒"

参考

備考

  • 例にする時刻を24時間表記と12時間表記のメリハリがつく時刻にすればよかった
0
3
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
0
3