I get the created date and time of a file us开发者_高级运维ing attributesOfItemAtPath:
. I get the NSString
as result which displays Date Created: 2011-08-23 10:47:33 +0000
. But, how can I retrieve the information about the date alone from the NSString
ignoring the information about time. i.e. my result should be like Date Created: 2011-08-23
.
Doesn't the attributesOfItemAtPath: return an NSDate? That's what the docs says. To get a string with just the date from an NSDate, use an NSDateFormatter. Code might look a bit like this:
NSDictionary* attributesDictionary = [[NSFileManager defaultManager] attributesOfItemAtPath: path error: NULL];
NSDate* date = [attributesDictionary objectForKey: NSFileCreationDate];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString* justDateString = [dateFormatter stringFromDate: date];
[dateFormatter release];
You'r actual getting back an NSDate
not string:
NSString *filePathName = [directory stringByAppendingPathComponent:fileName];
NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePathName error:&error];
// No attributes then jst skip the file
if (!attributes || error) {
NSLog(@"Error getting attributes for: %@\nWith error: %@", filePathName, error);
retun;
}
NSDate *modifiedDate = [attributes objectForKey:NSFileModificationDate];
With a NSDateFormatter
you get the string from that date:
NSDateFormatter *formatter = [[NSDateFormatter alloc]
[formatter setDateFormat:@"yyyy-MM-dd"];
NSString *datestring = [formatter stringFromDate:modifiedDate];
[formatter release], formatter = nil;
精彩评论