Need to convert NSString to Nsdate

2019-08-21 17:20发布

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];
}

2条回答
在下西门庆
2楼-- · 2019-08-21 18:08

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);
查看更多
仙女界的扛把子
3楼-- · 2019-08-21 18:18

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:.

查看更多
登录 后发表回答