Subscribe. Follow. Stalk.

Wednesday, August 8, 2012

N days ago Objective-C

What app could I possibly be making?
As I was working on a new iOS app, I realized that the best way to display the information that I had stored as a timestamp was to create a function that could change the seconds from 1970 to more informative messages like "3 seconds ago" or "2 days ago"

After searching the web for a while (on Bing, because I live in the Seattle area) I found this website with a very helpful snippet of code to create what I wanted. The problem was that it was in PHP! Oh dear, I'm not working on PHP, it looks like I will have to keep on searching...

Sadly after searching, I still couldn't find anything relating to objective c and this time ago function. I decided that it would be faster for me to just simply port the code to Objective-C.

Then I remembered my promise last Monday. So here is the first piece of code you will see from me on this blog. (Yes, I can in fact code)

+ (NSString *)ago:(int)time {
    char * periods[] = {"second", "minute", "hour", "day", "week", "month", "year", "decade"};
    double lengths[] = { 60, 60, 24, 7, 4.35, 12, 10};
    int now = [NSDate timeIntervalSinceReferenceDate] + NSTimeIntervalSince1970;
    double difference = now - time;
    int j;
    for(j = 0; difference >= lengths[j] && j < 6; j++) {
        difference /= lengths[j];
    difference = round(difference);
    NSString * result = [NSString stringWithUTF8String:periods[j]];;
    if (difference != 1) {
        result = [result stringByAppendingString:@"s"];
    return [NSString stringWithFormat:@"%d %@ ago", (int)difference, result];
The class method takes an int for the seconds since 1970. It returns an NSString but can easily be adapted to return a C string if you so incline to do so. Also, if you're one of the strange few people who do high-level programming with pure C, you would only need to change the NSDate to the current unix timestamp in C in addition to eliminating the NSString mentioned earlier.

Yup that's it! If you want this method available to other classes, I advise you declare it in the header.

1 comment: