使用nsdateformatter从字符串中获取日期

时间:2013-04-09 11:54:45

标签: iphone xcode nsdateformatter

我遇到一些问题,从字符串中获取正确的日期。我的代码如下:

NSDateFormatter* df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSLog(@"ex date == %@", [df dateFromString:@"2013-04-09 15:57:17"]); 

并按照此2013-04-09 10:27:17 +0000打印 它应该显示这样,应该像这样打印2013-04-09 15:57:17 有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

使用我的方法...

-(NSString *)changeDateFormat:(NSString*)stringDate dateFormat:(NSString*)dateFormat getwithFormat:(NSString *)getwithFormat{


    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormatter setDateFormat:dateFormat];

    NSDate *date = [dateFormatter dateFromString:stringDate];

    dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormatter setDateFormat:getwithFormat];

    NSString *convertedString = [dateFormatter stringFromDate:date];
    NSLog(@"Converted String : %@",convertedString);
    return convertedString;
}

像下面那样使用它......

NSString *strSDate = [self changeDateFormat:@"2013-04-09 15:57:17" dateFormat:@"yyyy-MM-dd HH:mm:ss" getwithFormat:@"dd/MM/yyyy"];
NSLog(@"ex date == %@",strSDate );

它会打印..

ex date == 09/04/2013

请参阅My Blog...