Rails DateTime.now without Time

现在我需要使用 DateTime.now 来获取当前日期,并“去掉”时间。

例如,这显示了我 不要想要的: DateTime.now => Sat, 19 Nov 2011 18:54:13 UTC +00:00

这显示了我想要的 : DateTime.now.some_operation => 2011-11-06 00:00:00 UTC

139466 次浏览

Figured it out. This works:

DateTime.now.in_time_zone.midnight

What you need is the function strftime:

Time.now.strftime("%Y-%d-%m %H:%M:%S %Z")

If you're happy to require 'active_support/core_ext', then you can use

DateTime.now.midnight # => Sat, 19 Nov 2011 00:00:00 -0800

You can use one of the following:

  • DateTime.current.midnight
  • DateTime.current.beginning_of_day
  • DateTime.current.to_date

What about Date.today.to_time?

If you want today's date without the time, just use Date.today

You can use just:

Date.current