如何使用NSDateFormatter iOS格式化日期?

时间:2016-04-22 16:34:10

标签: ios objective-c nsdateformatter uidatepicker

我尝试使用NSDateFormatter格式化从UIDatepicker中选择的日期。但格式化结果给出了nil

-(NSString *)formatDateWithString:(NSString *)date{ 
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MMM-dd HH:mm:ss";
    NSDate *formattedDate = [dateFormatter dateFromString:date];
    return [dateFormatter stringFromDate:formattedDate];
}

日期输入为2016-04-22 16:30:36 +0000(从UIDatePicker中选择后)。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:5)

如评论中所述,您可以直接从UIDatePicker获取NSDate,并直接在格式化程序中传递该日期

NSDateFormatter * formatter =  [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MMM-dd HH:mm:ss"];
NSString *dateString = [formatter stringFromDate:datePicker.date];//pass the date you get from UIDatePicker

如果您想按照问题中提到的相同方式进行转换,可以尝试这样:

-(NSString *)formatDateWithString:(NSString *)date{
    NSDateFormatter * formatter =  [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss z"];
    NSDate * convrtedDate = [formatter dateFromString:date];
    [formatter setDateFormat:@"yyyy-MMM-dd HH:mm:ss"];
    NSString *dateString = [formatter stringFromDate:convrtedDate];
    return dateString;
}