0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails初学者】Railsの日付操作まとめ(備忘録)

Posted at

Railsの日付操作まとめ(自分の備忘録)

はじめに

RailsではActiveSupport::TimeWithZoneを利用することで、アプリのタイムゾーンを意識した日付・時間操作が可能です。
この記事は自分用の備忘録として、整理したものです。
間違えていたら、コメント頂けますとありがたいです。


現在時刻の取得

now = Time.current
  • Time.current: Railsのタイムゾーン設定を反映した現在時刻
  • Time.now: サーバーのシステム時刻(タイムゾーンを考慮しない)

過去・未来の計算

1.hour.ago       # 1時間前
1.hour.from_now  # 1時間後
1.day.ago        # 昨日
1.day.from_now   # 明日
1.month.ago      # 先月
1.month.from_now # 来月
1.year.ago       # 去年
1.year.from_now  # 来年

.ago.from_nowを覚えておけば直感的に書けるようです。


日付の始まりと終わり

Time.current.beginning_of_day   # 今日の0:00
Time.current.end_of_day         # 今日の23:59:59

Time.current.beginning_of_month # 今月の1日0:00
Time.current.end_of_month       # 今月の最終日23:59:59

Time.current.beginning_of_year  # その年の1月1日0:00
Time.current.end_of_year        # その年の12月31日23:59:59

期間(Range)の取得

Time.current.all_day     # 今日
Time.current.all_week    # 今週
Time.current.all_month   # 今月
Time.current.all_quarter # 今四半期
Time.current.all_year    # 今年

特定の日付を作る

specific = Time.zone.local(2024, 9, 2, 12, 0, 0)

Time.zone.localはアプリのタイムゾーンを考慮して日時を生成できます。


タイムゾーン変換

utc_time = specific.in_time_zone("UTC")

Tokyo時間で作った日時をUTCに変換する例。


表示フォーマット

now = Time.current
now.strftime("%Y年%m月%d日 %H時%M分%S秒")
# => "2025年10月02日 16時30分00秒"

strftimeのフォーマット指定子で自由に整形可能。


応用例

月初から月末までループ

start_date = Time.current.beginning_of_month
end_date   = Time.current.end_of_month

(start_date..end_date).each do |date|
  puts date.strftime("%Y-%m-%d")
end

タイムゾーン比較

tokyo = Time.zone.now
ny    = tokyo.in_time_zone("America/New_York")

if tokyo.today? == ny.today?
  puts "同じ日付"
else
  puts "日付が異なる"
end

来週の平日9時に予定を作成

next_week = 1.week.from_now

5.times do |i|
  meeting_time = next_week.beginning_of_week + i.days + 9.hours
  puts meeting_time.strftime("%Y-%m-%d %H:%M")
end

まとめ

  • RailsではTime.currentを使うのが基本
  • .ago, .from_nowで直感的に過去・未来を扱える
  • .beginning_of_*/ .end_of_*日付の境界を取得できる
  • .all_day / .all_weekなどは範囲検索に便利
  • Time.zone.localで特定日時を作り、in_time_zoneで変換可能

Railsの時間操作に慣れて、日付計算が必要な場面で積極的に活用していきたいです。

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?