简体   繁体   中英

Rails displays wrong date for object's created_at and updated_at

I have a problem in my application. I am making a simple CMS and I need to display posts' creation date. What I am doing now doesn't work correctly. It displays time correctly, but not the date. For every entry it shows that the date is 20th October, although it is not.

I checked my db via rails c , it stores correct values. So the issue must be somewhere in displaying code.

Here is how I output it:

<% @articles.each do |article| %>
  <h3 class="article-title"><u><%= link_to article.title, article %></u></h3>
  <p><%= article.text.html_safe %></p>
  <div class="article-info">
    <p>Posted on <em><%= article.updated_at.strftime("%A, %C %B %G %R") %> </em> by <em><%= article.user.username %></em> |
    <%= link_to 'Comments...', article %>
    <% if user_signed_in? and article.user == current_user %>
       | <%= link_to 'Edit', edit_article_path(article) %>
       | <%= link_to 'Destroy', article, method: :delete, data: { confirm: 'Are you certain you want to delete this?' } %> </p>
    <% end %>
    </div>
    <% if article.tag_list.any? %>
      <div class="article-tags">Tags: <%= raw article.tag_list.map { |tag| link_to tag, tag_path(tag)}.join(", ") %></div>
    <% end %>
  <hr />
<% end %>

What can cause such a behaviour?

Your Problem is the strftime attributes:

<%= article.updated_at.strftime("%A, %C %B %G %R") %>

%A - The full weekday name ( Sunday'') %C - year / 100 (round down. 20 in 2009) %B - The full month name ( January'') %G - The week-based year %R - 24-hour time (%H:%M)

You need to use the this:

<%= article.updated_at.strftime("%A, %d %B %Y %R") %>

%d - %d - Day of the month, zero-padded (01..31)

%Y - Year with century

APIdock - DateTime

在您的代码中使用这种格式

<%= article.updated_at.strftime("%A, %d %B %Y %l:%M%p") %>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM