I have a site that uses ruby (rhtml) files which I am not used to editing (more used to php). I only have access to these files to edit (so not the back-end).
In the database I have a date that I can display using:
<%= zp.date %>
which will display e.g. 14/10/2010
I can display today's date using:
<%= Date.today.strftime("%Y%m%d") %>
which will display 20160122.
What I'm trying to work out is how I can compare the dates and echo the difference and in turn display something different.
e.g.
compare <%= zp.date %> and <%= Date.today.strftime("%Y%m%d") %>.
If days difference is less than 20 echo XXX
else
If days difference between 20 - 40 echo XXX
else
If days difference between 41 - 60 echo XXX
Any help would be appreciated (links etc), code examples would be greatly appreciated.
Again to clarify I can only edit the rhtml.
Dates are directly comparable with if-statements, and computing the difference will show you the number of days between them. Assuming zp.date
is in the past:
<% date_difference = Date.today - zp.date %>
<% if date_difference < 20 %>
...
<% elsif date_difference <= 40 %>
...
<% elsif date_difference <= 60 %>
...
<% else %>
Difference is greater than 60
<% end %>
Note the <% %>
tags, which are used for if-logic and internal Ruby code - basically any expression that shouldn't be output (thanks @QPaysTaxes), instead of <%= %>
which is the output tag.
If you don't know whether zp.date
is in the past or future, you can use the abs
method on the result:
<% date_difference = (Date.today - zp.date).abs %>
And if zp.date
isn't actually a Date
object, then parse
it:
<% date_difference = (Date.today - Date.parse(zp.date)).abs %>
Older Ruby versions will need strptime
when the date string is ambiguous:
<% date_difference = (Date.today - Date.strptime(zp.date, '%d/%m/%Y')).abs %>