开发者

Why does my NSDateFormatter return nil when parsing?

开发者 https://www.devze.com 2022-12-22 01:05 出处:网络
my code is like this NSString *tempDate = [NSString stringWithString:tempReviewData.pubDate]; NSDateFormatter *dateFormatter = [[NSDateFormatter al开发者_如何学Pythonloc] init];

my code is like this

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

NSDateFormatter *dateFormatter = [[NSDateFormatter al开发者_如何学Pythonloc] 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


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


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消