更改 Rails 3 中日期输入的格式? [英] Change format for date input in Rails 3?

查看:40
本文介绍了更改 Rails 3 中日期输入的格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Rails 3 中使用 text_field 输入日期,并希望将日期格式化为 mm/dd/yyyy.

I am using a text_field for date input in Rails 3 and would like the date to be formatted as mm/dd/yyyy.

虽然我已经找到了一些以这种方式显示日期的解决方案,但我还没有遇到一种可行的方法来接受该格式作为输入.

While I've found a few solutions for displaying the date in that way, I haven't run across a workable method for accepting that format as an input.

问题在于,对于像 "09/05/2011" 这样不明确的日期,Rails 会将其解释为May 9th"而不是September 5th".

The problem is that in the case of ambiguous dates like "09/05/2011", Rails interprets it as "May 9th" rather than "September 5th."

让 Rails 3 根据 mm/dd/yyyy 格式解释这些类型的输入的最佳方法是什么?

What is the best way to get Rails 3 to interpret those sorts of inputs according to the mm/dd/yyyy format?

推荐答案

希望您的目标受众是美国人,因为美国以外的许多地方都不使用这种日期格式.

Hopefully your target audience is solely American, since that date format is not used many places outside the US.

无论如何,您只想验证字符串的格式:

Anyway, you just want to validate the format of the string:

validates_format_of :the_date, :with => /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/

这是一个非常基本的模式,它验证字符串的格式,但不验证分隔符之间的实际值.如果你想这样做,你最好的办法可能只是尝试用 Date#strptime 解析日期,看看它是否解析.

That's a very rudimentary pattern that validates the format of the string, but not the actual values between the separators. If you want to do that, your best bet is probably just to try parsing the date with Date#strptime and see if it parses or not.

这篇关于更改 Rails 3 中日期输入的格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆