NSDateFormatter未正确将NSString转换为NSdate

时间:2011-09-12 05:18:06

标签: iphone nsdate nsdateformatter

这是我用于转换的代码

NSString * dateString = @"9/12/2011";
NSDateFormatter *serverDateFormatter = [[NSDateFormatter alloc] init];
[serverDateFormatter setDateFormat:@"MM/dd/yyyy"];
NSDate *serverDate = [serverDateFormatter dateFromString:dateString];
[serverDateFormatter release];

输出是 2011-09-11 19:00:00 +0000

但我只想将该nsstring转换为具有相同格式的nsdate 9/12/2011

3 个答案:

答案 0 :(得分:1)

试试这个。

     NSString * dateString = @"9/12/2011";
NSDateFormatter *serverDateFormatter = [[NSDateFormatter alloc] init];
[serverDateFormatter setDateFormat:@"dd/MM/yyyy"];
NSDate *serverDate = [serverDateFormatter dateFromString:dateString];
NSLog(@"%@",serverDate);

NSDateFormatter *tempDate=[[NSDateFormatter alloc]init];
[tempDate setDateFormat:@"MM/dd/yyyy"];
   NSDate *date=(NSDate *)[tempDate stringFromDate:serverDate];
NSLog(@"%@",date);

[tempDate release];
[serverDateFormatter release];

希望这会对你有帮助..

答案 1 :(得分:0)

将此属性设置为NSDateFormatter

[serverDateFormatter setDateStyle:NSDateFormatterShortStyle];
[serverDateFormatter setTimeStyle:NSDateFormatterNoStyle];

答案 2 :(得分:0)

您可以尝试以下代码,因为我成功运行了该代码。

NSString * dateString = @"9/12/2011";
NSDateFormatter *serverDateFormatter = [[NSDateFormatter alloc] init];
[serverDateFormatter setDateFormat:@"d/MM/yyyy"];
NSDate *serverDate = [serverDateFormatter dateFromString:dateString];
NSLog(@"%@",serverDate);

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"d/MM/yyyy"];
NSDate *st = (NSDate *)[dateFormat stringFromDate:serverDate];
NSLog(@"%@",st);

它的回归9/12/2011所以试试吧。