Challenge: DateMonger, solution with formatter method


#1

I used one Class method to generate the date from components and one Instance method to format the date. I contemplated using a C helper function for the formatting stock with an instance method. Are there any advantages of one over the other?

main.m

[code]#import <Foundation/Foundation.h>
#import “NSDate+ZGCDateConvenience.h”

int main(int argc, const char * argv[]) {
@autoreleasepool {

    int dd = 10;
    int mm = 11;
    int yy = 2015;
    NSDate *myDate = [NSDate zgc_dateByIntYear:yy month:mm day:dd]; 
    
    NSLog(@"%@", [myDate zgc_dateFormatter]); 
    
}
return 0;

}

[/code]

NSDate+ZGCDateConvenience.h

[code]#import <Foundation/Foundation.h>

@interface NSDate (ZGCDateConvenience)

  • (NSDate *)zgc_dateByIntYear:(int)yy month:(int)mm day:(int)dd;
  • (NSString *)zgc_dateFormatter;

@end

[/code]

NSDate+ZGCDateConvenience.m

#import "NSDate+ZGCDateConvenience.h"

@implementation NSDate (ZGCDateConvenience)

+ (NSDate *)zgc_dateByIntYear:(int)yy month:(int)mm day:(int)dd {
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    comps.year = yy;
    comps.month = mm;
    comps.day = dd;
    comps.hour = 00;
    comps.minute = 00;
    comps.second = 00;
    comps.timeZone = [NSTimeZone localTimeZone];
    
    return [cal dateFromComponents:comps];
    
}

- (NSString *)zgc_dateFormatter {
    NSString *yourDate = [NSDateFormatter localizedStringFromDate:self
                                                        dateStyle:NSDateFormatterFullStyle
                                                        timeStyle:NSDateFormatterFullStyle];
    
    return yourDate;
}

@end