简体   繁体   English

DateTime无法在Rails中将字符串转换为日期

[英]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. 我正在寻找一个由datetimepcker生成的参数转换为“ 03/17/2019 8:30 AM”的参数。 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? 有人知道如何将datetime参数保存在rails中吗?

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 谢谢

The issue is you are asking for seconds in your strptime call, but your time doesn't have seconds. 问题是您在strptime通话中要求输入几秒钟,但是您的时间却没有几秒钟。 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. 或增加时间。

Your format string has :%S in it, but the string you're trying to parse doesn't have seconds in it. 格式字符串中包含:%S ,但是您尝试解析的字符串中没有秒。 Either remove that part of the format string or find some way for the date string to have seconds in it. 删除格式字符串的该部分,或者找到某种方式使日期字符串包含秒数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM