将字符串“MM / dd / yy”转换为日期MM / dd / yyyy

时间:2016-06-03 09:28:18

标签: ios iphone nsdate nsdateformatter

我尝试将字符串11/08/91(MM / dd / yy)转换为11/08/1991(MM / dd / yyyy),但它输出错误的输出链接 日期是:0091-11-07 18:06:32 +0000

  • 我的原始输出是11/08/1991

我的代码

NSString *strdate = @"11/08/91";

NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];

[dateformate setDateFormat:@"MM/dd/yyyy"];

NSDate *date = [dateformate dateFromString:strdate];

NSLog(@"Date is :%@",date);

2 个答案:

答案 0 :(得分:3)

试试这个会给出正确的日期,

  NSString *strdate = @"11/08/91";

NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];

[dateformate setDateFormat:@"MM/dd/yy"];

NSDate *date = [dateformate dateFromString:strdate];


NSLog(@"Date is :%@",date);

它会给1991-11-07 18:30:00 +0000

然后你可以这样做,

  [dateformate setDateFormat:@"MM/dd/yyyy"];

NSString *str = [dateformate stringFromDate:date];
NSDate *finalDate = [dateformate dateFromString:str];

它会给,

final date str is 11/08/1991

final date is 1991-11-07 18:30:00 +0000

答案 1 :(得分:2)

NSString *strdate = @"11/08/91";

NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];

[dateformate setDateFormat:@"MM/dd/yy"];

NSDate *date = [dateformate dateFromString:strdate];

[dateformate setDateFormat:@"MM/dd/yyyy"];
//date = [dateformate dateFromString:[dateformate stringFromDate:date] ];
NSLog(@"Date is :%@",[dateformate stringFromDate:date]);

输出为:日期是:11/08/1991