边栏以文字显示格式化的日期



我有这种格式的日期 2014-04-05 从 @post.date
在我看来,我想将其转换为这种格式"4 月 5 日星期六"。
如果日期是今天,我希望它使用这种格式"今天 4 月 6 日"目前我有

<% if @post.date === Date.today.strftime("%Y-%m-%d") %>
   <p> Today Month(short form) Day(number) </p>
<% else %>
   <p> Day(word) Month(short form) Day(number)  </p>
<% end %>

如何设置日期格式?
提前谢谢。

使用这个:

<% if @post.date === Date.today %>
   <%= @post.date.strftime("Today %b %d") %>
<% else %>
   <%= @post.date.strftime("%A %b %d") %>
<% end %>

请参阅可用于strftime格式指令的完整列表

一个更干净的解决方案是在"app/helpers/application_helper.rb"中将其实现为帮助程序方法

按如下方式定义方法:

def date_string_for(datetime) datetime.strftime("%b %e, %Y") end

然后,您可以从任何视图中调用:

<%= date_string_for @post.date %>

这提供了一个 DRY 解决方案。

最新更新