在 ruby 中解析和验证任意日期格式(在 Rails 上)
我需要在现有应用程序中处理自定义日期格式。这个想法是,用户必须处理来自他们几乎无法控制的外部来源的多种格式。我们需要能够采用该格式并根据它验证日期,以及专门解析该格式的字符串。另一件事是,这些可以是完全任意的,例如 JA == 一月,FE == 二月等...
据我了解,chronic 只处理解析(并且以比我可以使用的更神奇的方式进行),并且在此处输入代码 DateTime#strptime 很接近,但即使使用自定义格式化程序,也无法真正处理整个两个字符的月份场景。 “核”选项是为这样的边缘情况编写自定义支持,但如果存在这样的东西,我更愿意使用库。
I have a requirement to handle custom date formats in an existing app. The idea is that the users have to do with multiple formats from outside sources they have very little control over. We will need to be able to take the format and both validate Dates against it, as well as parse strings specifically in that format. The other thing is that these can be completely arbitrary, like JA == January, FE == February, etc...
to my understanding, chronic only handles parsing (and does it in a more magical way then I can use), and enter code here DateTime#strptime comes close, but doesn't really handle the whole two character month scenario, even with custom formatters. The 'nuclear' option is to write in custom support for edge cases like this, but I would prefer to use a library if something like this exists.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果格式确实非常任意,我认为不存在可以处理所有这些问题的东西。将您的输入“塑造”为可由
Date.parse
、Date.strptime
或其他现有工具处理的表单可能是最简单的,即使这可能意味着相当多的工作。我们正在谈论多少种不同的格式?它们有冲突吗?看起来你可以像这样
gsub
:input_string.gsub(/\bJA\b/i, 'January')
。这是导入例程的一部分,还是用户将以不同格式输入日期?这里有一个相关的问题:Parse Italian Date with Ruby
I don't think something that handles all these problems exists if the format is really very arbitrary. It would probably be easiest to "mold" your input into a form that can be handled by
Date.parse
,Date.strptime
, or another existing tool, even though that could mean quite a bit of work.How many different formats are we talking about? Do any of them conflict? It seems like you could just
gsub
like so:input_string.gsub(/\bJA\b/i, 'January')
. Is this part of an import routine, or are the users going to be typing in dates in different formats?There's a related question here: Parse Italian Date with Ruby