views:

314

answers:

3

my code is like this

NSString *tempDate = [NSString stringWithString:tempReviewData.pubDate];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateFormat:@"HH:mm a"];

NSDate *newDate = [dateFormatter dateFromString:tempReviewData.pubDate];

My newDate is getting nil at this point i dont know why

+1  A: 

It seems to work for me but it depends on the format of tempReviewData.pubDate.

When I use invalid format, like @"6:30 M", I get null as well.

This is working:

NSString *tempDate = [NSString stringWithString:@"6:30 PM"];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateFormat:@"HH:mm a"];

NSDate * newDate = [dateFormatter dateFromString:tempDate];
NSString * str = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"date: %@", newDate);
NSLog(@"str: %@", str);

Output:

2010-03-08 22:36:57.904 x[4340:903] date: 1970-01-01 12:30:00 +1000
2010-03-08 22:36:57.905 x[4340:903] str: 22:36 PM
stefanB
+1  A: 
NSDate *newDate = [dateFormatter dateFromString:tempReviewData.pubDate];

Does pubDate return an NSString, or an NSDate?

If it returns a string, then you should rename that property to clearly indicate that.

If it returns a date (NSDate), then trying to parse it as a string will not work, since it is not a string; moreover, you can cut out all this formatter code, since you already have the date object you're after.

Peter Hosey
A: 

It seems the NSDateFormatter has gotten very picky.

-(void)dateFormatterTests {
    NSDateFormatter *formatter;

    formatter = [[NSDateFormatter alloc] init];

#ifdef WORKS
    [formatter setDateFormat:@"yyyy-MM-dd"];
#elif defined(ALSO_WORKS)
    [formatter setDateFormat:@"yyyy MM dd"];
    [formatter setLenient:YES];
#else // DOESN'T WORK
    [formatter setDateFormat:@"yyyy MM dd"];
#endif

    // Works per comments above
    NSLog(@"dFS: %@", [formatter dateFromString:@"2010-01-13"]);  
    // Never works with any of the above formats
    NSLog(@"dFS: %@", [formatter dateFromString:@"2010-01-13 22:00"]); 

    [formatter release]; formatter = nil;
}
John Franklin