【问题标题】:iPhone sdk - Get date from NSFileCreationDateiPhone sdk - 从 NSFileCreationDate 获取日期
【发布时间】:2011-09-09 14:23:21
【问题描述】:

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

【问题讨论】:

    标签: iphone ios4 nsdate nsdateformatter


    【解决方案1】:

    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];
    

    【讨论】:

      【解决方案2】:

      您实际上得到的是 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;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多