Many a times, in an iPhone application, you might need to format the date relative to today. This code snippet will help you do it.

+ (NSString *) formattedDateRelativeToNow:(NSDate *)date
{
		NSDateFormatter *mdf = [[NSDateFormatter alloc] init];
	[mdf setDateFormat:@"yyyy-MM-dd"];
	NSDate *midnight = [mdf dateFromString:[mdf stringFromDate:date]];
	[mdf release];
 
	NSInteger dayDiff = (int)[midnight timeIntervalSinceNow] / (60*60*24);	
	NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];	
 
	if(dayDiff == 0) 
		[dateFormatter setDateFormat:@"'Today, 'h':'mm aaa"];
	else if(dayDiff == -1) 
		[dateFormatter setDateFormat:@"'Yesterday, 'h':'mm aaa"];
	else if(dayDiff == -2) 
		[dateFormatter setDateFormat:@"MMMM d', Two days ago'"]; 	
	else if(dayDiff > -7 && dayDiff <= -2) 
		[dateFormatter setDateFormat:@"MMMM d', This week'"]; 
	else if(dayDiff > -14 && dayDiff <= -7) 
		[dateFormatter setDateFormat:@"MMMM d'; Last week'"]; 
	else if(dayDiff >= -60 && dayDiff <= -30) 
		[dateFormatter setDateFormat:@"MMMM d'; Last month'"]; 
	else if(dayDiff >= -90 && dayDiff <= -60) 
		[dateFormatter setDateFormat:@"MMMM d'; Within last three months'"]; 
	else if(dayDiff >= -180 && dayDiff <= -90) 
		[dateFormatter setDateFormat:@"MMMM d'; Within last six months'"]; 
	else if(dayDiff >= -365 && dayDiff <= -180) 
		[dateFormatter setDateFormat:@"MMMM d, YYYY'; Within this year'"]; 
	else if(dayDiff < -365) 
		[dateFormatter setDateFormat:@"MMMM d, YYYY'; A long time ago'"];
 
	return [dateFormatter stringFromDate:date];
}

Link back if you liked it…



–Mugunth

Follow me on Twitter

If you enjoyed this post, make sure you subscribe to my RSS feed!

Related posts:

  1. Objective-C Singleton Template for XCode 4 Update:Nov 7th 2011: Get the latest ARC compatible template from...

  • http://www.sportingtimes.org/tag/english/ Shera Timperman

    Pretty impressive article. I just came across your site and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.

  • http://bytask.com wordpress developer

    Your site looks excellent. Being a blog author personally, I truly value the time you took in writing this article.

  • http://locksmithknoxville.com Locksmith Knoxville

    For some reason i’m receiving a blank page when i make an effort to post a comment,do you recognize reasons why its happening?i’m using oprea web-browser