Post Pic

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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.

Related posts:

  1. How to Create a Twitter Client on Windows Phone 7 It was only days ago when I installed the Windows...
  2. Looks like iPhone crash reports! Just connected my iPhone to sync it and charge it...
  3. sprintf with NSString A small snippet of code to show how to use...
  4. iPhone SDK 3.0 – Playing with Map Kit – Part 3 This is the 3 part of me Playing with Map...
  5. Twitter + iPhone = MyTweet A simple twitter client using Objective C API provided by...

Related posts brought to you by Yet Another Related Posts Plugin.

One Response

02.18.10

Good one….Very HelpFull Code….

Leave Your Response

* Name, Email, Comment are Required