Stephen Bannasch
10/1/2007 4:58:00 AM
At 4:08 PM +0900 9/23/07, Allen Young wrote:
>Hi all,
>
>I want to parse some strings into Date object and I find in rdoc that
>strptime is the right place to go. For some formats of string it's
>really easy to parse it. For instance, '%Y.%m.%d' will parse something
>like '2007.09.12'. But I have two kinds of string that I don't now how
>to parse.
>
>'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.
Hi Allen,
It surprises me that this isn't easier. Here's what I'm doing to convert a similar input date/time format.
s = "20070926.155656"
d, t = s.scan(/\d+/) # => ["20070926", "155656"]
d1 = "#{d[0..3]}-#{d[4..5]}-#{d[6..7]}" # => "2007-09-26"
t1 = "#{t[0..1]}:#{t[2..3]}:#{t[4..5]}" # => "15:56:56"
dt = "-#{d1}T#{t1}Z" # => "-2007-09-26T15:56:56Z"
dt1 = DateTime.parse(dt) # => #<DateTime: 10673317777/10800,0,2299161>