This question already has an answer here:
I have a string like this
NSString *datestr = @"2013-08-06T03:51:54+00:00";
I try to set dateformat as below:
NSDateFormatter *dformat = [[NSDateFormatter alloc]init];
[dformat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
NSDate *date = [dformat dateFromString:datestr];
But the date will be nil, so, can anyone tell me how to set the dateformat, thx!
Try this:
NSDateFormatter *dformat = [[NSDateFormatter alloc]init];
[dformat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];
NSDate *date = [dformat dateFromString:datestr];
Add ZZZ
to the end of your formatter.
Try out this code
NSString *datestr = @"2013-08-06T03:51:54+00:00";
NSDateFormatter *dformat = [[NSDateFormatter alloc]init];
[dformat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssz"];
NSDate *date = [dformat dateFromString:datestr];
use small z where z give you - with the specific non-location format. Where that is unavailable, falls back to localized GMT format. Use one to three letters for the short format or four for the full format. In the short format, metazone names are not used unless the commonlyUsed flag is on in the locale
for zone for more info about Date Format Patterns in objective c refer this link http://www.unicode.org/reports/tr35/tr35-19.html#Date_Format_Patterns hope this will help you
try below:
NSString *dateString = @"2013-08-06T03:51:54+00:00";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZ";
NSDate *date;
NSError *error;
[formatter getObjectValue:&date forString:dateString range:nil error:&error];
来源:https://stackoverflow.com/questions/18098647/ios-how-to-set-date-format