Zeeshan Raja
Zeeshan Raja

Reputation: 145

Updating time in iphone sdk

I'm using the code provided below to display time and date. can anyone help me with atuomatically changing the time by seconds and the date by the day?

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];

NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"HH:mm:ss"];

NSDate *now = [[NSDate alloc] init];

NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];

NSLog(@"\n"

      "theDate: |%@| \n"
      "theTime: |%@| \n"
      , theDate, theTime);

[dateFormat release];
[timeFormat release];
[now release];

Upvotes: 0

Views: 2597

Answers (3)

drewh
drewh

Reputation: 10167

Use the NSDateComponents class. For example, to add one day and one second to a date:

NSDate *startDate = [NSDate date];
unsigned unitFlags = NSDayCalendarUnit | NSSecondCalendarUnit;

NSCalendar *curr = [NSCalendar currentCalendar];
NSDateComponents *oneDay = [[NSDateComponents alloc] init];
oneDay.day = 1;
oneDay.second = 1;

NSDate* adjustedDate = [curr dateByAddingComponents:oneDay 
                                             toDate:startDate 
                                            options:0]; 

Upvotes: 1

notnoop
notnoop

Reputation: 59299

You can use NSTimer, specifically scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:. You can use 1 as a time interval.

Upvotes: 3

slf
slf

Reputation: 22767

Date and Time programming guide

Upvotes: 0

Related Questions