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.
Hi, i have a question, i have tried to used the NSDate+Formatting methods, but every time i call the distanceOfTimeInWords method or any other, i get an unrecognized selector send to instance inside my ios app. Dou you have any suggestion about what could be happening?
Thanks,
Without seeing your code, I can only guess. How are you including the files in your build? Are you calling distanceOfTimeInWords on an NSDate instance? Is the example project on github working for you?