Previously, to exclude seconds from datetime,
we had to parse datetime using strftime
.
Before
Let’s say we have a Product
model
and we need to show purchased_at
as a date time field excluding seconds.
This is our ProductsController
.
class ProductsController < ApplicationController
def show
@product = Product.find(params[:id])
render :show
end
end
And this is how our views/products/show.html.erb
would look like.
<h1>Product Detail</h1>
<table class="table table-hover">
<tbody>
<tr>
<%= form_with model: @product do |form| %>
<%= datetime_field("product", "purchased_at", value: @product.purchased_at.strftime("%Y-%m-%dT%H:%M")) %>
<% end %>
</tr>
</tbody>
</table>
And this is how it will get rendered on the browser.
After
Now, Rails allows adding a include_seconds
option to datetime_field
,
using which we can include/exclude the seconds.
<h1>Product Detail</h1>
<table class="table table-hover">
<tbody>
<tr>
<%= form_with model: @product do |form| %>
<%= datetime_field("product", "purchased_at", include_seconds: false) %>
<% end %>
</tr>
</tbody>
</table>
This is how a browser renders it.
And suppose we need to include the seconds,
we can pass include_seconds
as true
.
<h1>Product Detail</h1>
<table class="table table-hover">
<tbody>
<tr>
<td>
<%= form_with model: @product do |form| %>
<%= datetime_field("product", "purchased_at", include_seconds: true) %>
<% end %>
</tr>
</tbody>
</table>
Check out the PR for more details.