Allen Young wrote: > > '20070912': there is no '.', '-' or '/' as the seperator and '%Y%m%d' > doesn't work, it will throw an exception saying that: "ArgumentError: 3 > elements of civil date are necessary". > > '2007.09': in this kind of string, I don't care about the exactly > date(in fact, the data I received is lacked of that information). As a > result, '%Y.%m' doesn't work with the same error as above. > > How can I deal with this two kinds of string? Thanks a lot. Try this: require "parsedate" include ParseDate str = '20071029' arr = parsedate(str) p arr #[2007, 10, 29, nil, nil ...] begin d = Date.new(arr[0], arg[1], arr[2]) puts d.year #2007 puts d.month #10 rescue ArgumentError puts "invalid date, eg. month = 15" end str = '2007.9' arr = parsedate(str) p arr #[nil, 20, 7, nil, nil ...] pieces = str.split(".") begin d = Date.new(Integer(pieces[0]), Integer(pieces[1]), 1) puts d.year #2007 puts d.month #9 rescue ArgumentError puts "invalid date, e.g. day = 32" end -- Posted via http://www.ruby-forum.com/.