ActiveRecord的日期格式日期、格式、ActiveRecord

2023-09-08 16:00:38 作者:  τ坏@男朲 τ坏@女朲

我碰到的麻烦与日期格式在我们的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.

不过,活动记录,似乎在期待的的 MM / DD / YY 的。

However, Active Record seems to be expecting mm/dd/yy.

如果我输入的的 01/03/2010 的,这被放在为 2010 01月03日的。

If I enter 01/03/2010, this gets put in as 03 January 2010.

如果我输入的的 25/03/2010 的,这个被放入的的空的

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的日期时间尝试自动检测格式。它会检测以下格式: 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] 作为一个字符串再presentation的日期。请检查您的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).