Forum: Ruby DateTime beauty

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
7f891fbe8e3bae7f9fe375407ce90d9d?d=identicon&s=25 hhausman (Guest)
on 2005-11-15 06:09
(Received via mailing list)
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
992fe8c19bbbc27f2b562a9f96efc03d?d=identicon&s=25 jamis (Guest)
on 2005-11-15 06:36
(Received via mailing list)
It should just be a matter of using strftime:

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

- Jamis
7f891fbe8e3bae7f9fe375407ce90d9d?d=identicon&s=25 hhausman (Guest)
on 2005-11-15 06:45
(Received via mailing list)
Wow, that works like a charm, thanks.

-Harold
Dce0999389d102f9a313af625375304c?d=identicon&s=25 dooby (Guest)
on 2005-11-15 07:18
(Received via mailing list)
Harold Hausman wrote:
> On 11/14/05, Jamis Buck 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 :)


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
This topic is locked and can not be replied to.