I want to convert NSString to NSdate and back using category. I'm having trouble in calling.
+ (NSDate*)stringDateFromString:(NSString*)string
{
NSString *dateString = @"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];
return dateFromString;
}
+ (NSString*)StringFromDate :(NSDate*)date
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@", stringDate);
return stringDate;
}
Based on the code you have provided you will need to create a category as follows:-
NSString+Utils.h
NSString+Utils.m
And to call either method:-
Please be aware that allocating NSDateFormatter is expensive so you might not want to be doing too many calls to these methods (in a table view for example).
Output from XCTestCase