I want to print my timestamp objects in a specific format. I want to
print
a date like this:
Sunday, January 8 2006
I don’t want it to print January 08.
For the time, I want it to look like this:
9:08 pm
Not 09:08 and lower case PM. I created these methods:
def format_date(date)
date.strftime("%A, %B #{date.day} #{date.year}")
end
def format_time(date)
if date.hour > 12
hour = date.hour - 12
elsif date.hour == 0
hour = 12
else
hour = date.hour
end
time = "#{hour}:#{date.min} "
if date.hour > 12
time += “pm”
else
time += “am”
end
end
There has to be a better way to do this. Any ideas?
BTW - How do I know what the datatype of the properties that are created
by
AcitveRecord::Base are?
Paul B. wrote:
I want to print my timestamp objects in a specific format. I want to
print
a date like this:
Sunday, January 8 2006
I don’t want it to print January 08.
For the time, I want it to look like this:
9:08 pm
Not 09:08 and lower case PM. I created these methods:
Try this for the time format
def format_time(date)
date.strftime("%I:%M %p") =~ /(0*)([\d:]+) (\w+)/
“#{$2} #{$3.downcase}”
end
Use a regexp to find 08 and replace it with 8? There’s not a cleaner
way to
do that?
Paul B. wrote:
I want to print my timestamp objects in a specific format. I want to
print
a date like this:
Sunday, January 8 2006
I don’t want it to print January 08.
For the time, I want it to look like this:
9:08 pm
Not 09:08 and lower case PM. I created these methods:
def format_date(date)
date.strftime("%A, %B #{date.day} #{date.year}")
end
There has to be a better way to do this. Any ideas?
Check out ActiveSupport Time and Date conversion modules. They extend
to_s to take a symbol specifying the format to use, eg
“Time.now.to_s(:db)” converts the time to the canonical database
representation of a datetime. Then you can put something like the
following in your environment.rb file:
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
:date_time12 => “%m/%d/%Y %I:%M%p”,
:date_time24 => “%m/%d/%Y %H:%M”
)
The use a regexp and .downcase to finish the job.
BTW - How do I know what the datatype of the properties that are created
by
AcitveRecord::Base are?
AR::columns returns an array of columns.
Try printing
MyModel.columns.collect {|c| [c.name, c.type]}
Also, when I print Time.zone, I get “Eastern Standard Time”. How can I
get
“EST” instead?