字符串转换为日期格式未知的iphone

时间:2013-09-05 07:42:26

标签: iphone ios objective-c

我在服务器上有这样的日期字符串“2013-09-05T06:40:19Z” 我想将它转换为日期,哪种格式应该与我的iphone相同。

怎么做? 当我这样做的时候?

NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];       
[dateFormatter1 setDateFormat:@"MMM dd yyyy"];       
[dateFormatter1 setLocale:[NSLocale currentLocale]];        
[dateFormatter1 setTimeZone:[NSTimeZone systemTimeZone]];       
NSDate *date =[dateFormatter1 dateFromString:time];
NSLog(@"%@",date)//getting null here 

我的约会时间为空。

3 个答案:

答案 0 :(得分:2)

NSString *dateStr = @"2013-09-05T06:40:19Z";
NSString *outDateFormate = @"MMM dd yyyy";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setLocale:[NSLocale currentLocale]];
    [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *intime = [dateFormat dateFromString:dateStr];
    [dateFormat  setDateFormat:outDateFormate];
    NSString *dateWithNewFormat = [dateFormat stringFromDate:intime];

答案 1 :(得分:0)

NSString *str=@"2013-09-05T06:40:19Z";
str=[[str stringByReplacingOccurrencesOfString:@"T" withString:@" "]stringByReplacingOccurrencesOfString:@"Z" withString:@""];
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
[dateFormatter1 setLocale:[NSLocale currentLocale]];
[dateFormatter1 setTimeZone:[NSTimeZone systemTimeZone]];
NSDate *date =[dateFormatter1 dateFromString:str];
[dateFormatter1 setDateFormat:@"MMM dd yyyy"];
NSString *newDate=[dateFormatter1 stringFromDate:date];

NSLog(@"%@",newDate)

答案 2 :(得分:0)

由于您以指定的格式获取日期,因此您需要相应地定义日期格式化程序

 NSString *gameDateString = @"2013-09-05T06:40:19Z";

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
 dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];  
 [dateFormatter setLocale:[NSLocale currentLocale]];
 [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]]; 

 NSDate *gameDate = [dateFormatter dateFromString:gameDateString];
 NSLog@("** The date is %@",gameDate); 

   // Now convert date to string in the format which you required.
  [dateFormatter  setDateFormat:@"MMMM dd, yyyy"];
  NSString *dateString =  [dateFormatter stringFromDate:gameDate];
  NSLog@("** The date string is %@",dateString); 

希望这有帮助。