LoginSignup
2
0

More than 1 year has passed since last update.

【Ruby】指定日付内のランダムな日時を取得する

Posted at

結論

rand関数で取得できます。
クラスに関係なく使えて便利。

# DateTime(時間は0時0分で固定の様子)
> datetime_from = DateTime.parse('2022-01-01 00:00:00')
> datetime_to   = DateTime.parse('2022-12-31 00:00:00')
> rand(datetime_from..datetime_to)
=> Sat, 30 Apr 2022 00:00:00 +0000

# Time(ミリ秒まで細かくランダムにしてくれる)
> time_from = Time.parse('2022-01-01 00:00:00')
> time_to   = Time.parse('2022-12-31 00:00:00')
> rand(time_from..time_to)
=> 2022-12-05 14:34:05 113996677/134217728 +0000

# ActiveSupport::TimeZone(秒まで)
> timezone_from = Time.zone.parse('2022-01-01 00:00:00')
> timezone_to   = Time.zone.parse('2022-12-31 00:00:00')
> rand(timezone_from..timezone_to)
=> Sat, 04 Jun 2022 13:29:32 JST +09:00

ちなみに

fromとtoのClassが異なっても一部成功しますが、バグの原因になりそうなのでやめておいたほうがいいかもしれません。

# DateTime..Time
> rand(datetime_from..time_to)
=> Sun, 23 Feb 9631 10:32:33 +0000
> rand(datetime_from..time_to).class
=> DateTime

# DateTime..ActiveSupport::TimeZone
> rand(datetime_from..timezone_to)
=> Sat, 07 Nov 76296 09:35:29 +0000
> rand(datetime_from..timezone_to).class
=> DateTime

# Time..ActiveSupport::TimeZone
> rand(time_from..timezone_to)
=> 2022-03-28 15:44:21 685943787/1073741824 +0000
> rand(time_from..timezone_to).class
=> Time

# ActiveSupport::TimeZone..Time
> rand(timezone_from..time_to)
=> Thu, 13 Jan 2022 10:04:04 JST +09:00
> rand(timezone_from..time_to).class
=> ActiveSupport::TimeWithZone

# Time..DateTime
> rand(time_from..datetime_to)
TypeError: expected numeric

# ActiveSupport::TimeZone..DateTime
> rand(timezone_from..datetime_to)
TypeError: expected numeric
2
0
2

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