0

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

Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103
Felix
  • 5,452
  • 12
  • 68
  • 163

3 Answers3

1

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.

Community
  • 1
  • 1
Surya
  • 15,703
  • 3
  • 51
  • 74
  • thanks, but when I do this: I got this: `2015-04-15T01:59:00+00:00` but I need this: `2015-04-15 01:59:00 +0100`, I need datetime as result – Felix Apr 13 '15 at 07:38
  • 1
    @Felix : It's `DateTime` object, which you can format later as per your convenience. Lookup the methods for formatting it `2015-04-15 01:59:00 +0100`. Shouldn't be a problem. – Surya Apr 13 '15 at 08:34
  • your right thats no problem :) Thanks for your help – Felix Apr 13 '15 at 08:50
  • Sorry for asking again, with puts it is printed correctliy in shell, but while storing it dosn't work corretly. puts says this: `2015-04-13 02:04:00` and in database its this: `2015-04-13 00:04:00` any idea whats going wrong? My code looks like this: `@datetime = @datetime.strftime("%Y-%m-%d %H:%M:00")` – Felix Apr 13 '15 at 09:01
  • thanks it works now. just `@datetime.strftime("%Y-%m-%d %H:%M:00")` is the solution – Felix Apr 13 '15 at 09:29
  • @Felix : I am glad that you've sorted it out yourself. That's the spirit, and I encourage you to keep it that way. Otherwise you won't be able to learn things by yourself. Good luck. :) – Surya Apr 13 '15 at 10:36
1

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

mgrim
  • 1,284
  • 12
  • 16
1

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.

Ryan Francis
  • 635
  • 6
  • 7