Search code examples
ruby-on-railsrubydatetime-select

Ruby on Rails converting date


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


Solution

  • 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.