Rene Chan
Rene Chan

Reputation: 985

DateTime not working to convert string to date in rails

I am looking to convert a parameters which is generated as: "03/17/2019 8:30 AM" by a form with datetimepcker. All the other parameters in the form are saved, except the time/date one. I tried multiple approaches but all failed.

2.5.3 :010 > a
 => "03/17/2019 8:30 AM" 
2.5.3 :011 > DateTime.strptime(a, "%m/%d/%Y %I:%M:%S %P")
Traceback (most recent call last):
        2: from (irb):11
        1: from (irb):11:in `strptime'
ArgumentError (invalid date)

This should be a simple issue, but does not seem to work out for me. Anybody knows how to save the datetime params in rails please?

The field in the form is as follow:

<div class="input-group date" id="datetimepicker4" data-target-input="nearest">
<%= f.text_field(:start, value: f.object.start ? f.object.start.strftime('%B %d, %Y') : nil, class: "form-control datetimepicker-input", data: {target:"#datetimepicker4"}, placeholder: "#{t :From}") %>
<div class="input-group-append" data-target="#datetimepicker4" data-toggle="datetimepicker">
<div class="input-group-text"><span class="fas fa-calendar-alt"></span></div>
</div>
</div>

Thank you

Upvotes: 1

Views: 498

Answers (2)

hashrocket
hashrocket

Reputation: 2222

The issue is you are asking for seconds in your strptime call, but your time doesn't have seconds. Try this instead:

a = "03/17/2019 8:30 AM"
DateTime.strptime(a, "%m/%d/%Y %I:%M %P")

Or add seconds to your time.

Upvotes: 3

Max
Max

Reputation: 1957

Your format string has :%S in it, but the string you're trying to parse doesn't have seconds in it. Either remove that part of the format string or find some way for the date string to have seconds in it.

Upvotes: 1

Related Questions