DateTime beauty

H

Harold Hausman

I've got strings created by doing something on the order of
DateTime.now.to_s stored away.

When I'm reading them out, and showing them to the user I want to see
something pretty like:

Sat Mar 10 at 12:34pm

Heres the code I came up with:

def timeFormat( in_str )
=09the_date =3D DateTime.parse( in_str )
=09the_date =3D the_date.new_offset( -7.0/24.0 )
=09nice_date =3D ''
=09nice_date +=3D case the_date.cwday
=09=09when 1; "Mon "
=09=09when 2; "Tue "
=09=09when 3; "Wed "
=09=09when 4; "Thu "
=09=09when 5; "Fri "
=09=09when 6; "Sat "
=09=09when 7; "Sun "
=09end
=09nice_date +=3D case the_date.month
=09=09when 1; "Jan "
=09=09when 2; "Feb "
=09=09when 3; "Mar "
=09=09when 4; "Apr "
=09=09when 5; "May "
=09=09when 6; "Jun "
=09=09when 7; "Jul "
=09=09when 8; "Aug "
=09=09when 9; "Sep "
=09=09when 10; "Oct "
=09=09when 11; "Nov "
=09=09when 12; "Dec "
=09end
=09nice_date +=3D the_date.day.to_s + ' at '
=09the_minute =3D the_date.min
=09if( the_minute < 10 )
=09=09the_minute =3D "0"+the_minute.to_s
=09else
=09=09the_minute =3D the_minute.to_s
=09end
=09if( the_date.hour < 12 )
=09=09nice_date +=3D the_date.hour.to_s + ":" + the_minute + "am"
=09elsif( the_date.hour > 12 )
=09=09nice_date +=3D ( the_date.hour-12 ).to_s + ":" + the_minute + "pm"
=09else
=09=09nice_date +=3D ( the_date.hour ).to_s + ":" + the_minute + "pm"
=09end
=09nice_date
end

#Woah, ugly.
#Anyone spare a moment to show me the right way to do something like this?

#Thanks in advance
#-Harold
 
J

Jamis Buck

It should just be a matter of using strftime:

value.strftime("%a %b %e at %I:%M%p")

- Jamis
 
D

daz

Harold said:
Wow, that works like a charm, thanks.


Just ignore this, then :)


require 'date'

def time_fmt2(str)
DateTime.parse(str).
new_offset(-7/24.0).
strftime('%a %b %d at %I:%M%p').
sub(/[AP]M\z/) {|xm| xm.downcase}
end

p time_fmt2('2005/11/15 05:59') # "Mon Nov 14 at 10:59pm"


daz
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top