Monday, February 25, 2008

Rails Time and Database

Last few days I improved rails code related to time function in several places.

1.

Rails extended basic Time class to give output in several format. So that you can output in database datetime format by passing :db symbol as argument to Time's to_s() method. Previously I produced database format manually
Time.now.strftime("%Y-%m-%d %H:%M:%S").to_s
now, it simplifies to
Time.now.to_s(:db)
Detail documentation can be found here

2.
To parse database date to ruby Time, I used this.
Time.parse(token.created_at.to_s)
where created_at is DateTime type field in Token model

3.
To get back-and-forth between Unix Timestamp and ruby Time, you can simply use -
Time.now.to_i
and to read -
Time.at(unix_timestamp)