无法使用NSDateFormatter从stringparsingdate
我坚持了一段时间在使用NSDateFormatter
stringparsingdate
string中的date格式如下
1/1/2011 12:00:00 AM
以下是我用来parsing的代码
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 @“2011年12月31日”和格式@“MM / dd / yyyy”
请帮忙
使用我的波纹pipe自定义方法,并将该dateparsing为另一种格式…
-(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; }
使用这种方法像波纹pipe..
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 =>转换string:01/01/2011
尝试这个
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]);