8

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!

Tarek Hallak
  • 18,422
  • 7
  • 59
  • 68
billwang1990
  • 627
  • 2
  • 6
  • 16

3 Answers3

12

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.

Abdullah Shafique
  • 6,878
  • 8
  • 35
  • 70
6

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

user1548843
  • 670
  • 12
  • 20
  • Also keep in mind that your format strings can be magically rewritten in some regions sometimes https://developer.apple.com/library/ios/qa/qa1480/_index.html – Earlz Jun 09 '15 at 19:10
1

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];
Tarek Hallak
  • 18,422
  • 7
  • 59
  • 68