在 ruby​​ 中解析和验证任意日期格式(在 Rails 上)

发布于 2024-09-03 07:10:11 字数 291 浏览 10 评论 0原文

我需要在现有应用程序中处理自定义日期格式。这个想法是,用户必须处理来自他们几乎无法控制的外部来源的多种格式。我们需要能够采用该格式并根据它验证日期,以及专门解析该格式的字符串。另一件事是,这些可以是完全任意的,例如 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无畏 2024-09-10 07:10:11

如果格式确实非常任意,我认为不存在可以处理所有这些问题的东西。将您的输入“塑造”为可由 Date.parseDate.strptime 或其他现有工具处理的表单可能是最简单的,即使这可能意味着相当多的工作。

我们正在谈论多少种不同的格式?它们有冲突吗?看起来你可以像这样gsubinput_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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文