Ruby-on-rails 在 Rails 中解析日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17563048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:18:47  来源:igfitidea点击:

Parse a date in rails

ruby-on-railsrubyruby-on-rails-3date-parsing

提问by Sachin Prasad

I have a date (Which is actually parsed from a PDF) and it could be any of the following format:

我有一个日期(实际上是从 PDF 解析出来的),它可以是以下任何一种格式:

MM/DD/YYYY
MM/DD/YY
M/D/YY
October 15, 2007
Oct 15, 2007 

Is there any gem or function available in rails or ruby to parse my date? Or I need to parse it using regex?

rails 或 ruby​​ 中是否有可用的 gem 或函数来解析我的日期?或者我需要使用正则表达式解析它?

BTW I'm using ruby on rails 3.2.

顺便说一句,我在 rails 3.2 上使用 ruby​​。

回答by Chris Heald

You can try Date.parse(date_string).

你可以试试Date.parse(date_string)

You might also use Date#strptimeif you need a specific format:

Date#strptime如果您需要特定格式,您也可以使用:

> Date.strptime("10/15/2013", "%m/%d/%Y")
=> Tue, 15 Oct 2013

For a general solution:

对于一般解决方案:

format_str = "%m/%d/" + (date_str =~ /\d{4}/ ? "%Y" : "%y")
date = Date.parse(date_str) rescue Date.strptime(date_str, format_str)

回答by beanie

I find the chronic gem very easy to use for time parsing and it should work for you. i tried the examples you gave.

我发现慢性宝石非常易于用于时间解析,它应该适合您。我试过你给出的例子。

https://github.com/mojombo/chronic

https://github.com/mojombo/chronic