I can print the date today using the code DateTime.now.strftime("%d/%m/%Y %H:%M")
But what if I want to combine some of it with string such as DateTime.now.last_month.strftime("25/%m/%Y 00:00")
Is it possible to achieve this?
I want to select the 25th day of the last month and use it in a condition.
This condition if DateTime.now.strftime("%d/%m/%Y %H:%M") > DateTime.now.last_month.strftime("25/%m/%Y 00:00")
returns false (with string)
While this condition if if DateTime.now.strftime("%d/%m/%Y %H:%M") > DateTime.now.last_month.strftime("%d/%m/%Y %H:%M")
returns true (without string)
If I properly understood what you are looking for, you are after getting 25th of the previous month. Use 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
Now compare whatever you want against it.
You can also do something like this for getting 25th date of month
DateTime.current.last_month.beginning_of_month + 24.days
=> Mon, 25 Jun 2018 00:00:00 +0000
@mudasobwa answer will work.
But I guess it can be done a little bit safer from using - 1.month
by using .ago
Example: ma = 1.month.ago
Then you can add this piece that he wrote: DateTime.new(ma.year, ma.month, 25, 0, 0, 0, "+00:00")
Also when you can compare the dates, it's better to use UTC so you don't compare two datetimes with different timezones
Example: if your_datetime.utc > ma.utc
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.