DateTime beauty


#1

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

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

#Thanks in advance
#-Harold


#2

It should just be a matter of using strftime:

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

  • Jamis

#3

Wow, that works like a charm, thanks.

-Harold


#4

Harold H. wrote:

On 11/14/05, Jamis B. wrote:

It should just be a matter of using strftime:

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

Wow, that works like a charm, thanks.

Just ignore this, then :slight_smile:

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