Tuesday, June 27, 2006

Ruby convert Time to Date

On more than one occasion I've needed to convert a Time object to a Date. Generally, I use the following code:
Date.parse(Time.now.strftime('%Y/%m/%d'))
I have two questions.
  • Is there a better way?
  • Why doesn't Time have a to_date method?

4 comments:

  1. ActiveSupport implements Time#to_date. If you're not working on a Rails application, you could always borrow their implementation.

    ReplyDelete
  2. Anonymous7:55 AM

    No kidding!

    Date, Time, and File objects in ruby could learn something from the Java core API. Oh well.

    ReplyDelete
  3. James6:57 AM

    Using strftime isn't necessary. You just do:
    Date.parse(Time.now.to_s)

    (replace Time.now with your date object!)

    ReplyDelete

Note: Only a member of this blog may post a comment.