So, you want to either do some calculations using dates or you just want to break up the time into hours, minutes and seconds.??
This is easy to do, using the built-in NSDate class within Xcode. Prior to the 2.2.1 iPhone update, I used a different method, but this was ‘broken’ by the update, as once built it under 2.2.1 I had several build warnings, which was only resolved with the following code.
A pain I know, and it took a couple of hours to sort it out.
Anyway, here is the code;
// Get the time NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit; NSDate *date = [NSDate date]; NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date]; // Turn the date into Integers NSInteger year = [dateComponents year]; NSInteger month = [dateComponents month]; NSInteger day = [dateComponents day]; NSInteger hour = [dateComponents hour]; NSInteger min = [dateComponents minute]; NSInteger sec = [dateComponents second];
Once you have the different integer variables, you can perform your calculations as required!
I don’t find the Apple documentation all that great and it’s severely lacking on how to do this sort of thing…
Happy coding!
Cheers
Graham
Thank you from Denmark!!
Wow! Thank you very much!
apple doc really no detail
Thank you. I’m a former J2EE programmer but now I moved to iPhone. Glad to see that the way to manage dates is more or less the same, NSGregorianCalendar rings a bell in my mind…