ActiveRecord 日期格式 [英] ActiveRecord date format
问题描述
我在 Rails 应用程序中遇到了日期格式问题.
I've run into a spot of bother with date formats in our Rails application.
我的视图中有一个日期字段,我想将其格式设置为 dd/mm/yy.这是用户期望输入日期的方式,日期选择器控件使用这种格式.
I have a date field in our view which I want to be formatted as dd/mm/yy. This is how the user will expect to enter their dates, and the datepicker control uses this format.
然而,Active Record 似乎期待 mm/dd/yy.
However, Active Record seems to be expecting mm/dd/yy.
如果我输入 01/03/2010,则输入为 2010 年 1 月 3 日.
If I enter 01/03/2010, this gets put in as 03 January 2010.
如果我输入 25/03/2010,它会被放入 null.
If I enter 25/03/2010, this gets put in a null.
如何让 ActiveRecord 期待女王陛下的日期格式?
How do I get ActiveRecord to expect Her Majesties date format?
推荐答案
Rails 的 DateTime 尝试自动检测格式.它将检测以下格式:mm/dd/yy
或 dd-mm-yy
或 yyyy-mm-dd
或 yyyy/mm/dd
.您可以对 DateTime.parse
进行猴子补丁,但我宁愿将此问题移至您的应用程序的视图.
Rails' DateTime tries to detect the formatting automatically. It will detect the following formats: mm/dd/yy
or dd-mm-yy
or yyyy-mm-dd
or yyyy/mm/dd
. You could monkey-patch DateTime.parse
, but I would rather move this issue to the View of your application.
我总是建议使用 yyyy-mm-dd [hh:mm:ss]
作为日期的字符串表示.检查您的 DatePicker 文档是否支持多种日期格式.
I always recommend to use yyyy-mm-dd [hh:mm:ss]
as a string representation for a date. Check the documentation of your DatePicker if it supports multiple date-formats.
例如,jQuery 日期选择器将其覆盖为 dateFormat
(对于发送到服务器的数据,将其设置为 yyyy-mm-dd
)作为以及 altFormat
(对于用户看到的输入,将其设置为 dd/mm/yyyy
).
The jQuery date-picker for example has this covered with dateFormat
(for the data that is sent to the server, set this to yyyy-mm-dd
) as well as altFormat
(for the input the user sees, set this to dd/mm/yyyy
).
这篇关于ActiveRecord 日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!