开发者

Can Rails automatically parse datetime received from form text_field

开发者 https://www.devze.com 2023-01-18 07:54 出处:网络
Can R开发者_开发百科ails automatically parse a datetime received from a form\'s text_field? # in view

Can R开发者_开发百科ails automatically parse a datetime received from a form's text_field?

# in view
<div class="field">
  <%= f.label :created_at %><br />
  <%= f.textfield :created_at %>
</div>

# in controller
params[:product][:updated_at].yesterday

Currently I'm get following error:

undefined method `yesterday' for "2010-04-28 03:37:00 UTC":String


If you are putting that param into a model directly, as the rails generator boilerplate code does, ActiveRecord takes care of that for you

def create
    @product = Product.new(params[:product])
    @product.updated_at.yesterday #will succeed
    #rest of method
end

Other than that you are stuck with something like:

DateTime.parse(params[:product][:update_at])

or

DateTime.civil_from_format(:local, year, month, day, hour, minutes, seconds)

But, in my experience .civil_from_format doesn't work as you'd expect with daylight savings time.

0

精彩评论

暂无评论...
验证码 换一张
取 消