无法使用NSDateFormatter从字符串中解析日期

时间:2013-04-23 06:33:00

标签: iphone ios objective-c nsdate nsdateformatter

我使用NSDateFormatter

在字符串中解析日期一段时间

字符串中的日期格式如下

  

1/1/2011 12:00:00 AM

以下是我用来解析的代码

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss"];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSDate *date = [[NSDate alloc]init];
date = [dateFormatter dateFromString:@"1/1/2011 12:00:00 AM"];

此代码适用于date @“12/31/2011”,格式为@“MM / dd / yyyy”

请帮忙

2 个答案:

答案 0 :(得分:2)

使用我的波纹管自定义方法并将该日期解析为另一种格式......

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

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

    NSDate *date = [dateFormatter dateFromString:stringDate];

    [dateFormatter setDateFormat:getwithFormat];

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

像下面这样使用这个方法..

 NSString *strSDate = [self changeDateFormat:@"1/1/2011 12:00:00 AM" dateFormat:@"dd/MM/yyyy hh:mm:ss a" getwithFormat:@"dd/MM/yyyy"];
 NSLog(@"Converted String : %@",strSDate);

getwithFormat参数中设置您想要的任何格式,并在dateFormat参数中设置您使用日期字符串的格式...

OUTPUT IS =>转换字符串:01/01/2011

答案 1 :(得分:0)

试试这个

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm:ss a"];
//First format date from string
NSDate *date = [dateFormatter dateFromString:@"01/01/2011 12:00:00 AM"];

//Set date formatter to specific format
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];

//Log the value
NSLog(@"%@",[dateFormatter stringFromDate:date]);