Its Saturday, 2:00 PM and my Michigan Wolverines are have a football game at 3:30PM. I’m rushing to get out of the house and on my way to Ann Arbor. My girlfriend asks me, “how long before the game starts?”
There are lots of answers to that question. 90 minutes, 1 hour and 30 minutes, an hour and a half, etc. The last one is probably the most natural for a human to say.
So how do you convert a time you get from a computer into a natural spoken amount of time?
It is fairly easy, there are just lots of little things. For example, if there is one hour, people often say “an” hour. Also, if there is only one hour you say “hour” instead of hours”. Same goes for minutes. Then there are half hours, quarter hours, and on and on.
I put together a simple little objective-c class that will convert a number in minutes into an NSString that would sound like a more natural duration.
// // NaturalTimeConverter.h // LocationBlaster // // Created by Randall Brown on 9/27/10. // Copyright 2010 FARP. All rights reserved. // #import <Foundation/Foundation.h> @interface NaturalTimeConverter : NSObject { } +(NSString*)stringWithNaturalTime:(NSInteger)numberOfMinutes; @end
// // NaturalTimeConverter.m // LocationBlaster // // Created by Randall Brown on 9/27/10. // Copyright 2010 FARP. All rights reserved. // #import "NaturalTimeConverter.h" @implementation NaturalTimeConverter +(NSString*)stringWithNaturalTime:(NSInteger)numberOfMinutes { int hours = numberOfMinutes / 60; int minutes = numberOfMinutes % 60; NSString* timeString; if (hours == 0 ) { if( minutes == 30 ) { timeString = @"half hour"; } else if( minutes == 1 ) { timeString = @"minute"; } else { timeString = [NSString stringWithFormat:@"%i minutes"]; } } else if( hours == 1 ) { if( minutes == 30 ) { timeString = @"hour and a half"; } else if( minutes == 1 ) { timeString = @"hour and 1 minute"; } else { timeString = [NSString stringWithFormat:@"hour and %i minutes", minutes]; } } else { if( minutes == 30 ) { timeString = [NSString stringWithFormat:@"%i and a half hours", hours]; } else if( minutes == 1 ) { timeString = [NSString stringWithFormat:@"%i hours and 1 minute", hours]; } else { timeString = [NSString stringWithFormat:@"%i hours and %i minutes", hours, minutes]; } } return timeString; } @end
Feel free to use and modify the code as you see fit. It probably doesn’t do everything everyone needs but at least it is a start.