当我形成一周或一个月时,NSDateFormatter总是返回nil,为什么?

时间:2016-06-10 05:48:20

标签: objective-c swift

测试如下

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = @"EEE";
        NSDate *createDate = [fmt dateFromString:@"Fri"];
        NSLog(@"%@",createDate);
        fmt.dateFormat = @"MMM";
        createDate = [fmt dateFromString:@"May"];
        NSLog(@"%@",createDate);
        fmt.dateFormat = @"dd HH:mm:ss Z yyyy";
        createDate = [fmt dateFromString:@"08 11:51:54 +0800 2016"];
        NSLog(@"%@",createDate);
    }
    return 0;
}

enter image description here

但是使用 Swift 语言,没有问题。

var str = "Wed Jun 08 11:51:54 +0800 2016"

var fmt = NSDateFormatter()
    fmt.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"

var date = fmt.dateFromString(str);

var str2 = fmt.stringFromDate(date!);

enter image description here

var str = "Wed Jun"

var fmt = NSDateFormatter()
    fmt.dateFormat = "EEE MMM"

var date = fmt.dateFromString(str);

var str2 = fmt.stringFromDate(date!);

enter image description here 我想知道为什么以及如何在 Objective-C 中处理这个问题。非常感谢!

1 个答案:

答案 0 :(得分:0)

从字符串中获取日期:

NSString *dateString = @"10-06-2016";
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
[fmt setDateFormat:@"dd-MM-yyyy"];
NSDate *date = [[NSDate alloc] init];
date = [fmt dateFromString:dateString];

转换为我们所需的日期格式:

[fmt setDateFormat:@"EEEE, MMMM dd, yyyy"];
NSString *reqDateString = [fmt stringFromDate:date];
NSLog(@"date is %@", reqDateString);