2013-02-07 48 views
0

我有以下的方法,我想用回修改日期:格式化的NSDate不工作

- (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; 
} 

的问题是格式化的日期是回来为空。

输出:

创建无格式的日期:2013年2月6日4时44分57秒+0000

格式化创建日期:(空)

+1

您需要查看文档。 'description'没有定义的返回格式;你试图依靠无证行为。我建议你再读一遍'NSDate'是什么;你似乎已经发明了一种观念,即它没有时就有格式。这只是一个特定时刻的不透明表示。 – Tommy

+2

你的代码有太多错误,很难知道从哪里开始。 –

回答

3

有没有这样的事情格式化的NSDate。这只是一个没有格式的日期。描述方法用于调试和记录,并使用任何想要的格式。

NSDateFormatter用于以指定的格式创建NSDate的NSString表示。你的方法可以用这个替换,做同样的事情。

- (NSDate *)getCreationDate:(NSFileManager *)fileManager atPath:(NSString *)path { 
    NSError *error; 
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:&error]; 

    // Get creation date. 
    if (!error) { 
     if (fileAttributes != nil) { 
      return [fileAttributes fileCreationDate]; 
     } else { 
      NSLog(@"File attributes not found."); 
     } 
    } else { 
     NSLog(@"%@", [error localizedDescription]); 
    } 

    return nil; 
} 

如果要显示日期,请格式化。使用NSDateFormatter将其转换为格式化的NSString。

此外,该行

date = [[NSDate alloc] init]; 
    date = [dateFormatter dateFromString:dateString]; 

创建一个新的日期,然后把它扔掉。第一行是不必要的。

+2

谁能负责解释对这个答案的投票?这是正确的:'NSDate's没有格式。 'fileCreationDate'是你直接从属性中获得的东西。即使他对日期格式化程序的使用完全错误,也不清楚为什么原始作者想要创建一个日期,然后将其丢弃并用格式化程序替换它。 – Tommy

+0

+1绝对正确。 –

+0

积分。谢谢。 – fuzz

0

你不纳入时间区域转换为时间格式,并且时间格式错误。它应该是

yyyy-MM-dd HH:mm:ss ZZZZ 
+1

而downvote的原因是:*** ??? *** – 2013-02-07 00:54:06

+0

它仍然返回null与您的答案以及。我没有downvote或btw。 – fuzz

+1

@gotnull从那以后我做了一个编辑 - 检查日期的格式(不仅仅是时间)。还要确保该字符串不包含任何无关的空格。 – 2013-02-07 00:59:55