iPhone sdk - 从NSFileCreationDate获取日期

时间:2011-09-09 14:23:22

标签: iphone ios4 nsdate nsdateformatter

我使用attributesOfItemAtPath:获取文件的创建日期和时间。我得到NSString作为显示Date Created: 2011-08-23 10:47:33 +0000的结果。但是,如何从NSString忽略有关时间的信息来检索有关日期的信息。即我的结果应该像Date Created: 2011-08-23

2 个答案:

答案 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;