Formatting Dates
Posted by Jonathan | Posted in rhomobile | Posted on 28-09-2011
0
Dates suck. Simple fact, no matter what language you’re using, formatting, date-math, converting or parsing dates … it all sucks.
So in an effort to try to limit the suck you have to go through if/when you have to deal with dates, I hope this helps.
My app, when first loaded, pulls a feed from our oracle database. The date is listed in the ‘typical’ format – 22-NOV-11, stores this in the device’s database (FixedSchema) ( property :session_date, :date ) – so you would think that would be the type date. In my controller I do this little query -
@days = Session.find_by_sql("SELECT distinct(session_date) _
FROM Session ORDER BY session_date")
In my view I loop through with something like this -
<% @days.each do |session| %>
typical, nothing special
so we essentially have session.session_date inside this loop – and I don’t want to display it in the default format (22-NOV-11). So I endevored on a painful journy – pulling in 3 other developers on the rhomobile list. 10 emails later, I got it working. I used this code -
@display_date = Date.strptime(session_date,"%d-%b-%y").strftime("%A, %B %d")
This gets me really close to the format I wanted, – Monday, November 23
But I wanted what I’ve found is called the ordinal suffix on the end ( the ‘rd’,'st’,'nd’,'th’). In rails there is an .ordinalize method – but that’s not available in ruby (maybe you could include a library or gem or something, but by this point, I’ve suffered 3 days to deal with this), so I created my own.
session_date = session.session_date @display_date = format_date(session_date)
in my session_controller.erb:
def format_date (date_in)
prefix = Date.strptime(date_in,”%d-%b-%
day = Date.strptime(date_in,”%d-%b-%
if day == 11 or day == 12
return prefix + “th”
else
case day % 10
when 1 then return prefix + “st”
when 2 then return prefix + “nd”
when 3 then return prefix +”rd”
else return prefix + “th”
end
end
end
might be a little klunky coding, I’m sure I could just set the suffix and append / return them at the end, but this works, and I need to move on to another part of my app.
theCodeDog
