格式化NSDate不起作用

时间:2013-02-07 00:47:18

标签: ios nsdate nsdateformatter

我有以下方法,我想用它来返回修改日期:

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

问题是格式化日期将返回null。

输出:

未格式化日期:2013-02-06 04:44:57 +0000

创建的格式化日期:( null)

2 个答案:

答案 0 :(得分: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];

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

答案 1 :(得分:0)

您没有将时区合并到时间格式中,并且小时的格式错误。它应该是

yyyy-MM-dd HH:mm:ss ZZZZ