17
Distance of Time in Words for Objective-C
Rails developers have the coolest tools, from migrations RVM to Bundler to Pow. One cool Rails tool lets you explain approximately how long ago something happened in words, with phrases such as:
- Less than 20 seconds ago
- About 3 minutes ago
- Over 3 years ago
You find this magic in date_helper.rb, in the distance_of_time_in_words method. I’m working on an iOS app that synchronizes with a Rails app that uses distance_of_time_in_words to describe how long ago certain events occurred, and I needed to mimic the web app’s description of how long ago things happened. I could have added the description to the JSON that the Rails app returns, but not only did that seem silly, but also it meant that iOS users would have to re-sync to get updated descriptions of how long ago things happened. Better to implement a “distance of time in words” capability for iOS.
After Google didn’t net me what I wanted, I decided to implement this in Objective-C, translating from the Ruby code. I opted to make this a category on NSDate, so you could get the distance of time in words using something like this:
NSDate *myDate; ... // Code that fills myDate ... NSString *words = [myDate distanceOfTimeInWords];
Along the way, I learned that Objective-C (and C) support ranges in switch statements, so I can do things like the Ruby code does, like this:
case 2 ... 44: number = minutes; measure = Minutes; break;
Notice the three dots between 2 and 44.
The result? A category called NSDate+Formatting, available on github at:
https://github.com/hoop33/DistanceOfTimeInWords
That repository includes not only the NSDate+Formatting category, but also a sample project that uses it. The sample project shows a date picker and a label. Spin the date picker to select a date, and the label shows the distance of time in words between now and the selected date. You can also toggle the date picker among Time, Date, and Date & Time modes. Finally, you click a button to reset the date picker to now. Here are some screenshots:



The code uses localized strings, so should be simple to localize into any language. It currently has both english and Spanish translations. I left Chile over 20 years ago, so feel free to correct my Spanish!
I’ve released this project under the Apache 2.0 license, which I think means that you can use it in your personal and commercial projects, and don’t have to put my name in the About box or strew petals in my path. Someone correct me if I’m wrong.
Leave a comment
What I’m Writing
Tech Books Deals of the Day
Blogroll
Archives
- May 2012 (3)
- April 2012 (4)
- March 2012 (8)
- February 2012 (7)
- January 2012 (7)
- December 2011 (1)
- November 2011 (1)
- September 2011 (4)
- August 2011 (2)
- July 2011 (2)
- June 2011 (2)
- May 2011 (4)
- April 2011 (2)
- February 2011 (1)
- January 2011 (1)
- December 2010 (3)
- November 2010 (3)
- October 2010 (4)
- September 2010 (6)
- August 2010 (96)







