如何在 Rails 上用 Ruby 中的字符串声明日期
How to declare a date with string in Ruby on Rails
我可以使用代码 DateTime.now.strftime("%d/%m/%Y %H:%M")
打印今天的日期
但是如果我想将其中的一些与 DateTime.now.last_month.strftime("25/%m/%Y 00:00")
之类的字符串结合起来怎么办?
有可能实现吗?
我想select上个月的第25天,并在一个条件下使用它。
这个条件 if DateTime.now.strftime("%d/%m/%Y %H:%M") > DateTime.now.last_month.strftime("25/%m/%Y 00:00")
returns false (with string)
虽然此条件 if if DateTime.now.strftime("%d/%m/%Y %H:%M") > DateTime.now.last_month.strftime("%d/%m/%Y %H:%M")
returns 为真(无字符串)
如果我正确理解你在找什么,你是在上个月的 25 号之后。使用 Time#new
:
ma = (DateTime.now - 1.month)
#⇒ Sun, 03 Jun 2018 11:07:24 +0200
DateTime.new(ma.year, ma.month, 25, 0, 0, 0, "+00:00")
#⇒ Mon, 25 Jun 2018 00:00:00 +0000
现在比较你想要的任何东西。
@mudasobwa 答案有效。
但我想通过使用 .ago
可以比使用 - 1.month
更安全一些
示例:ma = 1.month.ago
那你可以加上他写的这段:DateTime.new(ma.year, ma.month, 25, 0, 0, 0, "+00:00")
此外,当您可以比较日期时,最好使用 UTC,这样您就不会比较两个具有不同时区的日期时间
示例:if your_datetime.utc > ma.utc
您也可以这样做以获得每月的第 25 天
DateTime.current.last_month.beginning_of_month + 24.days
=> Mon, 25 Jun 2018 00:00:00 +0000
我可以使用代码 DateTime.now.strftime("%d/%m/%Y %H:%M")
但是如果我想将其中的一些与 DateTime.now.last_month.strftime("25/%m/%Y 00:00")
有可能实现吗?
我想select上个月的第25天,并在一个条件下使用它。
这个条件 if DateTime.now.strftime("%d/%m/%Y %H:%M") > DateTime.now.last_month.strftime("25/%m/%Y 00:00")
returns false (with string)
虽然此条件 if if DateTime.now.strftime("%d/%m/%Y %H:%M") > DateTime.now.last_month.strftime("%d/%m/%Y %H:%M")
returns 为真(无字符串)
如果我正确理解你在找什么,你是在上个月的 25 号之后。使用 Time#new
:
ma = (DateTime.now - 1.month)
#⇒ Sun, 03 Jun 2018 11:07:24 +0200
DateTime.new(ma.year, ma.month, 25, 0, 0, 0, "+00:00")
#⇒ Mon, 25 Jun 2018 00:00:00 +0000
现在比较你想要的任何东西。
@mudasobwa 答案有效。
但我想通过使用 .ago
- 1.month
更安全一些
示例:ma = 1.month.ago
那你可以加上他写的这段:DateTime.new(ma.year, ma.month, 25, 0, 0, 0, "+00:00")
此外,当您可以比较日期时,最好使用 UTC,这样您就不会比较两个具有不同时区的日期时间
示例:if your_datetime.utc > ma.utc
您也可以这样做以获得每月的第 25 天
DateTime.current.last_month.beginning_of_month + 24.days
=> Mon, 25 Jun 2018 00:00:00 +0000