Use NSDateFormatter To Create A Countdown App On iPhone

NSDateFormatter is excellent for date conversions in your iPhone App. We will use this to create a simple count down App. Here is core code using NSDateFormatter.

Remember that NSDate Object in Mac OSX and iPhone are different.


NSDate *date=[NSDate date];
int secondsNow=(int)[date timeIntervalSince1970];
NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy"];
int currentYear = [[formatter stringFromDate:date] intValue];
int nextYear=currentYear+1;
NSString *nextYearBegin=[NSString stringWithFormat:@"%d0101",nextYear];
[formatter setDateFormat:@"yyyyMMdd"];
NSDate *otherDate=[formatter dateFromString:nextYearBegin];
NSLog(@"%@",[otherDate description]);
int secondsTarget=(int)[otherDate timeIntervalSince1970];
int differenceSeconds=secondsTarget-secondsNow;
int days=(int)((double)differenceSeconds/(3600.0*24.00));
int diffDay=differenceSeconds-(days*3600*24);
int hours=(int)((double)diffDay/3600.00);
int diffMin=diffDay-(hours*3600);
int minutes=(int)(diffMin/60.0);
int seconds=diffMin-(minutes*60);
mDateTime.text=[NSString stringWithFormat:@"%d Days %d Hours %d Minutes %d Seconds",days,hours,minutes,seconds];

All the above code does is calculates the number of days, hours, minutes and seconds left for the upcoming new year of the current year. Line 1 will get you the current date object with current date and time. Then i use a NSDateFormatter to extract the year dynamically and figure out what the next year is. Then i use NSDateFormatter again to get a corresponding date object for January 1st of the next year.

Then some simple math to determine number days, hours, minutes and seconds. So using this code and a simple timer you can create a count down app to any date like Valentines day, Presidents Day or to your next vacation or birth day of your friend or spouse.

By: gavi on: