Ruby on Rails converting date

465 Views Asked by At

I'm using html5 datetime-local type

<input type="datetime-local" value="" name="start_date1"/>

it sends this to the controller: 2015-04-03T00:00

is it possible to convert it to this: 2015-04-03 00:00:00 +0100

3

There are 3 best solutions below

6
On BEST ANSWER

You can try changing params[start_date1] to the datetime:

require 'date' # not needed if you're using Rails
params[start_date1] = DateTime.strptime(params[start_date1], '%Y-%m-%dT%R')

Here:

%Y - Year with century (can be negative, 4 digits at least).

%m - Month of the year, zero-padded (01..12).

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

%R - 24-hour time (%H:%M).

Your params value "2015-04-03T00:00" is parsed with '%Y-%m-%dT%R' because, %Y is 2015, %m is 04, %d is 03, "T" tells that time is in 24 hours format. So, we'd just put it as is, and use %R to parse "hours:minutes".

You can read more about DateTime format directives here.

0
On

If you're using Rails, check out: github.com/launchpadlab/decanter

The basic idea is that this gem provides a place for you to transform your params before they hit your model. Kind of like the inverse of Active Model Serializers.

0
On

In Rails you should set your app's default time zone in config.time_zone. Then

Time.zone.parse(params[:start_date1])

will default to that time zone.

Time.zone can be overridden in runtime, see http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html#method-i-parse

You should also have a look at this: http://www.elabs.se/blog/36-working-with-time-zones-in-ruby-on-rails