Nov 282011

Those familiar with Django might know about the useful timesince template filter, which compares the interval between two dates and formats it into a human readable format. I wanted something like this in my iPhone app, so I wrote a category to do it.

The category adds a -timesince method to NSDate, which compares the date to the current time and returns the interval in an easy to read format. For example,

NSDate *d = [NSDate dateWithTimeIntervalSinceNow:-30020];
NSString *ts = [d timesince]; // 8 hours, 20 minutes

The category also has a -timesinceWithDepth: method, which controls how much precision you’d like in the output. For example,

NSDate *d = [NSDate dateWithTimeIntervalSinceNow:-30020];
NSString *ts = [d timesinceWithDepth:3]; // 8 hours, 20 minutes, 20 seconds

There is also a -timesinceDate:withDepth: method, which lets you compare the difference between any two arbitrary dates.

Find the code on GitHub as part of my RHTools repository.

 Leave a Reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>



This site uses Akismet to reduce spam. Learn how your comment data is processed.