Tuesday, January 5, 2010

Adding Date and Time to my Rails Blog App

For my blog posts and comments I wanted to display the date and time. Fortunately, the models automatically add the attribute created_at of datetime during the migration to the database. This allows me to just call the created_at attribute from the posts and comments table to display them after they have been created.


I got my first problem when I added it to my view. It appeared as 2009-12-14 08:25:51-1000. That's not what I wanted. I wanted December 14th, 2009 8:25AM. And this gave me another problem, the time was 10 hours off. I wanted Hawaii time so it should have been 2009-12-13 22:25:51-1000.


After a lot of searching I was able to piece together a solution. I have rails 2.3.3.


To format date and time I modified config/enviroment.rb. Looking at this file I found config.time_zone = 'UTC'. I didn't know what UTC was but above it had Run "rake -D time" for a list of tasks for finding time zone names. So I ran 'rake -D time' in my terminal and was given 'rake time:zones:local' which I ran and was given Hawaii as my time zone. So I changed config.time_zone = 'UTC' to config.time_zone = 'Hawaii'. This gave me my date and time but not the right format.


I wanted December 14th, 2009 8:25AM. To get this I had to create my format. I eventually found rails module for conversions. I then had to figure out what %Y-%m-%d meant. When I found the meaning I wrote the code below to display my date and time format. I also found to get 1 to display as 1st, 2 as 2nd, 14 as 14th, 23 as 23rd I had to add ordinalize to the day.


ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(

:time => '%I:%M%p',

:date => lambda { |time| time.strftime("%B #{time.day.ordinalize}, %Y") }

)


Format Meaning

%a The abbreviated weekday name (“Sun'’)

%A The full weekday name (“Sunday'’)

%b The abbreviated month name (“Jan'’)

%B The full month name (“January'’)

%c The preferred local date and time representation

%d Day of the month (01..31)

%H Hour of the day, 24-hour clock (00..23)

%I Hour of the day, 12-hour clock (01..12)

%j Day of the year (001..366)

%m Month of the year (01..12)

%M Minute of the hour (00..59)

%p Meridian indicator (“AM'’ or “PM'’)

%S Second of the minute (00..60)

%U Week number of the current year, starting with the first Sunday as the first day of the first week (00..53)

%W Week number of the current year, starting with the first Monday as the first day of the first week (00..53)

%w Day of the week (Sunday is 0, 0..6)

%x Preferred representation for the date alone, no time

%X Preferred representation for the time alone, no date

%y Year without a century (00..99)

%Y Year with century

%Z Time zone name

%% Literal “%'’ character



In my view I added:


%= comment.created_at.to_s(:date) %

%= comment.created_at.to_s(:time) %


Now every post and comment has a correct date and time.

No comments: