Parse a date in rails

后端 未结 2 1686
眼角桃花
眼角桃花 2020-12-10 01:06

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 
         


        
2条回答
  •  醉梦人生
    2020-12-10 01:16

    You can try Date.parse(date_string).

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

    > 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)
    

提交回复
热议问题