Need to convert NSString to Nsdate

最后都变了- 提交于 2019-12-13 02:59:52

问题


I need to convert "2013-05-05T00:00:00Z" this string to NSDate and again NSDate to Nsstring. I have tried with different-differnt format style but didn't get any success.

I have already checked.

NSDate from NSString

Convert NSDate to Sql Server Datetime format

Thanks.

// for getting string for Advance search  

-(NSDate*) doGetDateFromStringGSearch :(NSString*) dateStr 
{

NSDateFormatter * outputFormatter4 = [[[NSDateFormatter alloc ] init ] autorelease ];

NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[outputFormatter4 setLocale:locale];

//[outputFormatter4 setDateFormat: @"yyyy-MM-dd'T'HH:mm:ss:SSS"];
//[outputFormatter4 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"];
 [ outputFormatter4 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss:Z" ];
 //[ outputFormatter4 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss':00Z'" ];

NSString * inputString2 = dateStr;
NSDate * inputRecivedToDate = [outputFormatter4 dateFromString:inputString2 ];
NSLog(@"doGetDateFromString  %@", inputRecivedToDate);

return [[inputRecivedToDate retain] autorelease];
}

回答1:


Change you formatter string to :

[outputFormatter4 setDateFormat:@"yyyy-MM-dd'T'hh:mm:ss'Z'"];

The full code:

NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'hh:mm:ss'Z'"];
NSDate *date=[dateFormatter dateFromString:@"2013-05-05T00:00:00Z"];

NSLog(@"%@",date);



回答2:


I have been using the NSDateFormatter with @"yyyy-MM-dd'T'HH:mm:ssZZZZ" format for many years, but found out that on few, but only few (maybe less then 1%) of devices it was unsuccessful and was returning nil.

So as a fallback I have been using this library: https://github.com/keithpitt/ISO8601DateFormatter and now I am not seeing any issues with parsing ISO8601 date formats.

The library supports both dateFromString: and stringFromDate:.



来源:https://stackoverflow.com/questions/17120767/need-to-convert-nsstring-to-nsdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!