我正在尝试学习一些rails,它正在向前发展,但困扰我的是,正如标题所说,时间戳的结束。由于我是瑞典人,我修改了它以显示我正确的时区。
EG: 2014-08-20 13:24:51 +0200
但是我想看到的是2014-08-20 13:24
显示每个帖子的时间,我使用
<% @blog_posts.reverse_each do |blog_post| %>
<h3><%= blog_post.title %></h3>
<p> <%= blog_post.created_at.to_s %> </p>
<p>
<%= simple_format(blog_post.body) %>
</p>
<% end %>
谁有解决这个问题的简单方法? 在Rails中可以使用to_time函数将字符串转换为Date对象:
> '2014-8-20 14:27:46'.to_time.strftime('%B %e at %l:%M %p')
=> "August 20 at 2:27 PM"
strftime
格式指令:
-
%B
月名 -
%e
月的第几天 -
%l
一天中的小时数 -
%M
小时分钟 -
%p
子午线指示器(AM/PM)
Try
<%= blog_post.created_at.to_s %>
或者使用strftime:
<%= blog_post.created_at.strftime("%Y-%m-%d %H:%M") %>
您可以使用to_formatted_s
方法:
<%= blog_post.created_at.to_formatted_s(:db) %>
也会显示seconds
。如果您只想要日期、小时和分钟,请尝试:
<%= blog_post.created_at.strftime("%Y-%m-%d %H:%M") %>
查看ruby类Time中的strftime方法
<%= blog_post.cteated_at.strftime("%Y-%m-%d %H-%M") %>
这个链接可能也很有帮助Strfti.me
编辑:要本地化您的时间,您必须使用localalize或l => <%= l post。created_at %>首先从Rails语言环境文件中下载您的语言环境yml文件将原始文件复制到conconfig/locale。在这个文件中,你可以设置你的默认strftime:
formats: default: "%B %e at %l:%M %p"
然后在应用程序中。rb
config.i18 .default_locale =:pl//for me is pl:)
最后在你的视图
l blog_post.created_at
希望对你有帮助
try this.
<%= @user.created_at.to_date.to_formatted_s(:long_ordinal)%> => July 5th, 2014
<%=@user.created_at.strftime("%b %d,%Y") %> => Jul 05,2014
…