Clayton
Clayton

Reputation: 31

Finding the time in iphone programming

I need to find the current time for my iphone app. I need it broken up into the different units, so I need the hour, minute, and second in different variables. Please help!

Upvotes: 3

Views: 246

Answers (3)

zaph
zaph

Reputation: 112857

NSDate           *date           = [NSDate date];
NSCalendar       *calendar       = [NSCalendar currentCalendar];
NSCalendarUnit    unitFlags      = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];

NSInteger hour   = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];

NSLog(@"%ld:%ld:%ld", hour, minute, second); 

23:34:6

Upvotes: 1

bryanmac
bryanmac

Reputation: 39296

NSDate *date = [NSDate date];
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];

NSInteger year = [dateComponents year];
NSInteger month = [dateComponents month];
NSInteger day = [dateComponents day];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];

[calendar release];

Upvotes: 4

Alex Reynolds
Alex Reynolds

Reputation: 96927

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH"];
int hour = [[dateFormatter stringFromDate:[NSDate date]] intValue];
[dateFormatter setDateFormat:@"mm"];
int minute = [[dateFormatter stringFromDate:[NSDate date]] intValue];
[dateFormatter setDateFormat:@"ss"];
int second = [[dateFormatter stringFromDate:[NSDate date]] intValue];
[dateFormatter release];

Upvotes: 0

Related Questions