如何反转Date.parse()

时间:2012-09-11 15:06:22

标签: ruby ruby-on-rails-3.2

我的代码:

require 'Date'

s = "I'm going away on Oct 2, 2012th"
puts Date.parse(s)

=> 2012-10-02 

我想从Date.parse(s)找到的字符串中删除日期。问题是,我知道有一个日期,但不知道它是如何写在字符串中的。我知道Date.parse找到了它并将“2012-10-02”转换为新格式。

2 个答案:

答案 0 :(得分:0)

Date似乎无法告诉您发现日期的位置。您可能需要编写自己的自定义日期查找器。

答案 1 :(得分:0)

这是一个快速而肮脏的解决方案。函数date_string 只返回包含日期的字符串部分 由parse找到。

require 'date'

DATE_ERROR = -1

# If the string doesn't contain a date, it raises an
# exception.  This little helper routine catches the
# exception.
def get_date(s)
    date = 0
    begin
        date = Date.parse(s)
    rescue
        date = DATE_ERROR
    end
    date
end

# Returns just the part of the string containing the date
def date_string(s)
    # First, find the date contained in the string
    date = get_date(s)

    return "" if date == DATE_ERROR

    # Repeatedly chop off characters from the front to find the
    # start of the date
    first = 1
    while date == get_date(s[first..-1])
        first += 1
    end

    # Repeatedly chop off characters from the end to find the
    # end of the date
    last = s.length - 2
    while date == get_date(s[0..last])
        last -= 1
    end

    #Return just the date
    s[first - 1..last + 1]
end

puts date_string("I'm going away on Oct 2, 2012th")
puts date_string("I'm going away on 10/2/12 and not coming back")
puts date_string("10 Nov 1999")
puts date_string("I see no date here")

输出:

Oct 2, 2012
10/2/12
10 Nov 1999

所以你可以这样做:

s = "I'm going away on Oct 2, 2012th"
datestr = date_string(s)
s.gsub!(datestr, "")
puts s