I have the following method, which I want to use to return the modified date:
- (NSDate *)getCreationDate:(NSFileManager *)fileManager atPath:(NSString *)path {
NSError *error;
NSDate *date;
NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:&error];
// Get creation date.
if (!error) {
if (fileAttributes != nil) {
NSDate *creationDate = [fileAttributes fileCreationDate];
NSString *dateString = [creationDate description];
NSLog(@"Unformatted Date Created: %@", dateString);
// Format date.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy hh:mm:ss"];
date = [[NSDate alloc] init];
date = [dateFormatter dateFromString:dateString];
NSLog(@"Formatted Date Created: %@", [date description]);
} else {
NSLog(@"File attributes not found.");
}
} else {
NSLog(@"%@", [error localizedDescription]);
}
return date;
}
The problem is that the formatted date is coming back as null.
Output:
Unformatted Date Created: 2013-02-06 04:44:57 +0000
Formatted Date Created: (null)
There’s no such thing as a formatted NSDate. It’s just a date with no format. The description method is for debugging and logging and uses whatever format it wants.
NSDateFormatter is used to create an NSString representation of the NSDate with your specified format. Your method could be replaced with this and do exactly the same thing.
When you want to display the date, format it then. Use NSDateFormatter to turn it into a formatted NSString.
In addition, the lines
create a new date, then throw it away. The first line is unnecessary.