我使用attributesOfItemAtPath:
获取文件的创建日期和时间。我得到NSString
作为显示Date Created: 2011-08-23 10:47:33 +0000
的结果。但是,如何从NSString
忽略有关时间的信息来检索有关日期的信息。即我的结果应该像Date Created: 2011-08-23
。
答案 0 :(得分:3)
attributesOfItemAtPath:不返回NSDate吗?这就是文档所说的。要获取仅包含NSDate日期的字符串,请使用NSDateFormatter。代码可能看起来像这样:
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];
答案 1 :(得分:1)
你实际上找回NSDate
不是字符串:
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];
使用NSDateFormatter
,您可以获得该日期的字符串:
NSDateFormatter *formatter = [[NSDateFormatter alloc]
[formatter setDateFormat:@"yyyy-MM-dd"];
NSString *datestring = [formatter stringFromDate:modifiedDate];
[formatter release], formatter = nil;