views:

64

answers:

4

I am currently looking on converting Thu Jun 10 16:17:55 +0530 2010 to 15/06/2010 or 15-06-2010 using Ruby

I am getting the dates from the DB as shown below.

   @tickets = Ticket.find(:all)
   for ticket in @tickets
     print ticket.created_at
   end

I have been looking around for resources as I a n00b in RoR/Ruby.

I have looked at

and couldn't make much of it.

Please let me know how I could achieve this conversion in Ruby.

P.S: I have tried using regular expressions as well. But with no luck

+1  A: 

Do this.

   @tickets = Ticket.find(:all)
   for ticket in @tickets
     print ticket.created_at.strftime("%m/%d/%Y")
   end

For complete reference of strftime see here

Bragboy
But I get `undefined method `strftime' for #<Ticket:0x488c97c>` on doing this? Am I missing something?
dkris
I have edited the answer
Bragboy
Thanks much! Noticed you did an edit and it is working fine for me :)
dkris
You're most welcome...
Bragboy
+1  A: 
@tickets = Ticket.find(:all)
for ticket in @tickets
  print ticket.created_at.strftime("%d/%m/%Y")
end

Also you may want to check out the strftime method in Ruby's stdlib.

Eimantas
Thanks much! This helped
dkris
A: 

You're looking for a way to convert a string in the format Thu Jun 10 16:17:55 +0530 2010 to one in the in the format 15/06/2010, yes? For that you could to use strptime to create a new Date object, and then print it out using strftime, ie:

d = Date.strptime(ticket.created_at, '%a %b %d %H:%M:%S %z %Y')
print d.strftime('%d/%m/%Y')

Hope that helps.

Mitch Lindgren
Tried this. But i get `private method `sub!' called for Thu Jun 10 16:17:55 +0530 2010:Time` . Don't know what this means.
dkris
+3  A: 

If you are using Rails (which is indicated by your tag)

Date.today.to_s can take a parameter which represents a key in your DATE_FORMATS hash

A much better solution than #strftime, since its reusable without having to remember the #strftime incantation or having loads of helpers to do the same thing.

Omar Qureshi
Thanks much! I shall check this out
dkris