Variable datetimes

Hi, I have to store dates inside a DB, but unfortunately my date
representation can be a string like “2007” but also a normal date
string, like “2007-8-12” …
I want to use Date/DateTime objects because they are easy to
manipulate, but Date.parse can parse only the second format, not the
first (which is understandable …).
How can I solve this problem ? Storing something like 2007-0-0 or
2007-1-1 is ok for me, like in Date.new(2007).
I can check if the string contains ‘-’ and if not do something like
Date.new(string.to_i) but I don’t like this solution …

TIA,
ngw
Chiacchiera con i tuoi amici in tempo reale!
http://it.yahoo.com/mail_it/foot/*http://it.messenger.yahoo.com

string = ‘2007-01-01’
Date.new(*string.split(’-’).map(&:to_i))

Il giorno 09/ott/06, alle ore 03:22, Jonathan V. ha scritto:

string = ‘2007-01-01’
Date.new(*string.split(’-’).map(&:to_i))

Thank you, but my problem is that my input is only ‘2007’, if I had a
string like ‘2007-01-01’ I could use Date.parse :slight_smile:

ngw
Chiacchiera con i tuoi amici in tempo reale!
http://it.yahoo.com/mail_it/foot/*http://it.messenger.yahoo.com

On Oct 9, 3:33 am, Nicholas W. [email protected] wrote:

Il giorno 09/ott/06, alle ore 03:22, Jonathan V. ha scritto:

string = ‘2007-01-01’
Date.new(*string.split(’-’).map(&:to_i))Thank you, but my problem is that my input is only ‘2007’, if I had a
string like ‘2007-01-01’ I could use Date.parse :slight_smile:

ngw
Chiacchiera con i tuoi amici in tempo reale!
http://it.yahoo.com/mail_it/foot/*http://it.messenger.yahoo.com

irb:> string = ‘2007’
=> “2007”
irb:> Date.new(*string.split(’-’).map(&:to_i))
=> 2007-01-01

This seems to actually do what you want it to…

_Kevin

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs