18
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

フォームからdatetime_selectで送られてきた日付をDateTimeオブジェクトに変換する方法

Last updated at Posted at 2015-04-09

とっても面倒だったのでメモ

日時選択ボックス的なのをサクッと作ってくれるdatetime_selectですが、ちょっと癖がある
普通はありえないけど、例でUserモデルのcreated_atを更新するサンプルコードです。

= form_tag("/user/#{@user.id}", :method => :post) do
  = datetime_select(:created_at, :date, :default => @user.created_at)

POSTするとparams[:created_at]の中にいろいろはいってる

@user = User.find(params[:id])
@user.created_at = Time.zone.local(params[:created_at]["date(1i)"].to_i, params[:created_at]["date(2i)"].to_i, params[:created_at]["date(3i)"].to_i, params[:created_at]["date(4i)"].to_i, params[:created_at]["date(5i)"].to_i)
@user.save

DateTimeだとタイムゾーンを解釈してくれないので、Time.zone.localを使用して変換。

18
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?