skip to Main Content
Menu
Videoblocks Abstract Programming Code Background Software Development Concept Bdh5fisnx Thumbnail Full01

A few recipes about dates / using NSDate

The app I’ve been working lately makes a bit more use of NSDate than my usual ones. I thought I’d share with the world a few pieces of code I’ve been using;

How to test if two NSDate dates belong to the same day:

I created a category on NSDate and added the following method to it:

-(BOOL)isSameDay:(NSDate *) otherDate
{
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *comps_self = [[NSCalendar currentCalendar] components:unitFlags fromDate:self];
NSDateComponents *comps_other = [[NSCalendar currentCalendar] components:unitFlags fromDate:otherDate];

if ([comps_self day]==[comps_other day] &&
[comps_self month]==[comps_other month] &&
[comps_self year]==[comps_other year]) {
return YES;
}
return NO;
}
I can now call [mydate isSameDay:otherdate]

Find out the first and last days in the month that contains a given date

-(void) updateMonthIntervalForDate:(NSDate*)date{
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents* dc = [[NSCalendar currentCalendar] components:unitFlags fromDate:date];
dc.day=1;
NSDate* startOfMonth = [[NSCalendar currentCalendar] dateFromComponents:dc];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
offsetComponents.month=1;
NSDate* endOfMonth = [[NSCalendar currentCalendar] dateByAddingComponents:offsetComponents toDate:self.startVisibleDate options:0];
// … do whatever you want with startOfMonth and endOfMonth
}
Last but not the least, print out nicely Print out the full name of the month, or the abridged name

First of all, create a NSDateFormatter; the docs says it’s not inexpensive, so if you need it several times, try and reuse it instead of recreating it over and over again.

dateFormatter = [[NSDateFormatter alloc] init];
Next, decide the date format you want to output

Abridged version (like 01 Jan)
[dateFormatter setDateFormat:@”dd MMM”];
Full month name (January)
[dateFormatter setDateFormat:@”MMMM”];
Sure, this is in the docs as well, but I did quite a bit of searches to find out the part about MMMM for the full NSDate month name. So maybe it will help someone.

Once you have the date formatter ready, you can invoke it to get the nice string from your NSDate:

NSString* mystring = [[dateFormatter stringFromDate:crtEntry.date] uppercaseString];

Back To Top
Search