Converting a date format in objective C

前端 未结 2 1583
南方客
南方客 2020-12-09 15:04

How can i convert the following date \"Sun Jul 17 07:48:34 +0000 2011\" to the following format \"2011-07-17 07:48:34\"?

I used NSDateFormatter as shown

2条回答
  •  情歌与酒
    2020-12-09 15:43

    You've got your Date Format wrong for the style of Date you are passing in. Here is a document explaining the different modifiers: Date Format Patterns

    To parse the Date "Sun Jul 17 07:48:34 +0000 2011", you'd need a Format like so:

    [dateFormat setDateFormat:@"EEE MMM dd HH:mm:ss ZZZ yyyy"];
    

    To get it into the following format: "2011-07-17 07:48:34", here is the full code:

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"EEE MMM dd HH:mm:ss ZZZ yyyy"];
    NSDate *date  = [dateFormatter dateFromString:sDate];
    
    // Convert to new Date Format
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *newDate = [dateFormatter stringFromDate:date]; 
    

提交回复
热议问题