Rails 3:如何解决开发和生产环境中日期格式不一致的问题?
我的 Job 模型具有在迁移文件中定义的 job_date 字段,如下所示:
create_table :jobs do |t|
t.date "job_date", :null => false
[...]
end
在我的开发环境(在 Windows 上)中,当我这样做时:
job = Job.new(:job_date => "17/04/2011")
一切正常(即 < code>job_date 设置正确),而当我这样做时:
job = Job.new(:job_date => "04/17/2011")
job_date
设置为 nil
。
我猜这是因为数据库(MySQL)期望以 DD/MM/YYYY 格式获取日期。
问题是,在我的生产环境中,发生了完全相反的情况,即:
job = Job.new(:job_date => "04/17/2011")
正确设置“job_date”,而:
job = Job.new(:job_date => "17/04/2011")
将其设置为nil
。
我该如何解决这种不一致?
是否有某种方法可以将数据库配置为特定的日期格式(例如DD/MM/YYYY
)?
My Job
model has job_date
field that is defined in the migration file like this:
create_table :jobs do |t|
t.date "job_date", :null => false
[...]
end
In my development environment (on Windows), when I do:
job = Job.new(:job_date => "17/04/2011")
everything works fine (i.e. the job_date
is set properly), while when I do:
job = Job.new(:job_date => "04/17/2011")
job_date
is set to nil
.
I guess this is because the database (MySQL) expects to get the date in DD/MM/YYYY
format.
The problem is that in my production environment, exactly the opposite occurs, i.e.:
job = Job.new(:job_date => "04/17/2011")
sets the 'job_date` properly, while:
job = Job.new(:job_date => "17/04/2011")
sets it to nil
.
How could I solve this inconsistency ?
Is there some way to config the database for specific date format (like DD/MM/YYYY
) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不是数据库问题,但我认为这是 Ruby 中
Date.parse
方法的问题。事实上,当您调用 Job.new 时,它不会保存到数据库,只会创建模型的新对象。我相信 Rails 调用Date.parse
方法将字符串转换为日期对象,它在我的机器中给出了dd/mm/yyyy
格式的错误我认为 Rails 逃脱了这个错误并为此类值提供
nil
我猜你的生产环境的结果与我的机器和你的开发机器的 Ruby 相同,
Date.parse
可能适用于其他格式。如果您只需要处理一种格式(
dd/mm/yyyy
或mm/dd/yyyy
),则可以使用Date.strptime
在提供给数据库之前计算日期这将在您的生产和开发环境中以一种格式工作。
It is not a database problem, but I think it is a problem with
Date.parse
method in Ruby. Infact when you callJob.new
it is not saved to database only a new object of the model is created. I beleive Rails callDate.parse
method to convert the string into date object and it gives a error fordd/mm/yyyy
format in my machineI think Rails escape this error and gives
nil
for such valuesI guess your production environment's results are same like my machine and your development machine's Ruby,
Date.parse
may be working for the other format.If you need to handle only one format(Either
dd/mm/yyyy
ormm/dd/yyyy
), you can useDate.strptime
to calculate the date before giving to databaseThis will work both in your production and development environment for one format.