使用bootstrap-datepicker-rails,现在我的日期是字符串,但是我需要将日期另存为db [英] using bootstrap-datepicker-rails, now my dates are strings, but I need to save to db as dates
问题描述
经过很大的压力后,终于有了datepicker宝石成功地打开了一个迷你日历,并在字段中输入日期. 尽管使用了这个jQuery脚本,
After much stress, finally got the datepicker gem to succesfully open a mini-calendar and enter the date in the field. Despite using this jQuery script,
$jQuery ->
$(document).on "focus", "[data-provide~='datepicker']", (e) ->
- $(this).datepicker
- format: "yyyy-mm-dd"
- weekStart: 1
- autoclose: true;
...该字段中返回的日期仍为mm/dd/yyyy格式.只要我想在数据库中使用字符串字段就可以了(并且我可能会以这种方式重建数据库),但是我需要在start_date-end_date上做一些简单的数学函数,这就是为什么我用date创建数据库的原因字段,而不是字符串字段.
...the date returned in the field is still in mm/dd/yyyy format. That's fine as long as I want to use a string field in the database (and I may wind up reconstructing the db that way) but I need to do some simple math functions on start_date - end_date, which is why I created the database with date fields instead of string fields in the first place.
所以我需要做两件事之一-将我的数据库日期字段重新格式化为字符串(并在我的数学计算中使用Date.parse()),或者找到一种方法来保存返回到生成的文本字段的日期通过这个:
So I need to do one of two things--either reformat my db date fields to strings (and use Date.parse() in my math calculations) or find a way to save the date returned to the text field, generated by this:
<div class="field">
<%= f.label :end_date %><br>
<%= f.text_field :end_date, 'data-provide' => 'datepicker' %>
</div>
...作为mysql日期字段,格式为yyyy-mm-dd.提交表单之前,_form.html.erb文档中有没有办法做到这一点?
...as a mysql date field, formatted yyyy-mm-dd. Is there a way to do this in the _form.html.erb document prior to submitting the form?
或者,在bootstrap-datepicker-rails插件中是否存在参数/选项,该参数/选项将允许输入字段为日期字段而不是text_field,或者将返回值转换为日期而不是字符串?
Or, alternatively, is there a parameter/option in the bootstrap-datepicker-rails plugin that will allow the input field to be a date field instead of a text_field, or to convert the return value to a date instead of a string?
推荐答案
//在这里解决方案
object.date = Date.strptime(params [:date],'%m/%d/%Y').to_date
// here solution
object.date = Date.strptime(params[:date], '%m/%d/%Y').to_date
//根据您的代码更改日期格式
// change date format according your code
这篇关于使用bootstrap-datepicker-rails,现在我的日期是字符串,但是我需要将日期另存为db的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!