在 Rails 中解析日期 [英] Parse a date in rails

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

问题描述

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

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

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

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

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

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

BTW I'm using ruby on rails 3.2.

推荐答案

你可以试试 Date.parse(date_string).

You can try Date.parse(date_string).

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

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

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

通用解决方案:

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

这篇关于在 Rails 中解析日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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