Burak
Burak

Reputation: 5774

I cannot get string from NSDate

I have a [self.post post_time] NSDate with value of 2012-08-02T08:57:52.152713+00:00

NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
[formatter setDateFormat:@"yyyy-mm-dd"];
NSLog([formatter stringFromDate:[self.post post_time]]);

It doesn't work. What is the problem?

Upvotes: 0

Views: 146

Answers (2)

holex
holex

Reputation: 24041

first, the timezone does make you headache, because the NSDateFormatter can recognise the following formats for the timezones i.e. +0000 or GMT+1000 but it cannot recognise the timezones with colon, +00:00, simply, there is no pattern for it. so, somehow you should remove the colon from the timezone part.

second, you have to use the following pattern for your input date instead of the yyyy-mm-dd because this patter does not cover your input string.

NSString *_dateString = @"2012-08-02T08:57:52.152713+00:00";
NSString *_noColonInTimezone = [_dateString stringByReplacingCharactersInRange:NSMakeRange(_dateString.length-3, 1) withString:@""];
NSDateFormatter *_dateFormatter = [[NSDateFormatter alloc] init];
[_dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSZZZ"];
NSDate *_date = [_dateFormatter dateFromString:_noColonInTimezone];
NSLog(@"raw date : %@", _date);

it is working well, it has been tested on real device, I'm hoping it helps you to get the NSDate object with correct date and then you can format the date for the output as you wish.

Upvotes: 0

WhiteTiger
WhiteTiger

Reputation: 1691

your code works for me

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd'T'hh:mm:ss.SSSz"];
NSDate *myDate = [df dateFromString: @"2012-08-02T08:57:52.152713+00:00"]; // simulate your attribute

NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
[formatter setDateFormat:@"yyyy-MM-dd"];
NSLog(@"%@", [formatter stringFromDate:myDate]);

Upvotes: 1

Related Questions