Using NSDate for the time and/or date!

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 [...]

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

Tagged with:
 

4 Responses to “Using NSDate for the time and/or date!”

  1. Michael Nielsen says:

    Thank you from Denmark!!

  2. Thomas says:

    Wow! Thank you very much!

  3. jackie says:

    apple doc really no detail

  4. Daniele says:

    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… ;)

Leave a Reply




Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!