简体   繁体   中英

How to format date using NSDateFormatter iOS?

I tried to use the NSDateFormatter to format a date that selected from a UIDatepicker . But the formatted result giving a 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];
}

date input is 2016-04-22 16:30:36 +0000 (after selected from UIDatePicker). How may I fix this?

As mentioned in the comment you can get the NSDate directly from the UIDatePicker and pass that date directly in the formatter

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

If you want to convert the same way you have mentioned in the question you can try like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM