开发者

NSDateFormatter set date to 1970

In my summarydict, I have a entire called date_generated, it looks like : Sep 22, 2:33 PM, I want to convert it into a NSDate so that I can later feed it into a repeated timer.

So here's my code:

ALog(@"Last update time is: %@", [[summarydict objectForKey:@"root"]objectForKey:@"date_generated"]);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLenient:YES];
[dateFormatter setDateFormat:@"MM dd, h:mm a"];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"America/New_York"]];
NSDate 开发者_如何学C*date = [dateFormatter dateFromString:[[summarydict objectForKey:@"root"]objectForKey:@"date_generated"]];
ALog(@"Using timezone: %@", [dateFormatter timeZone]);
ALog(@"Last updated time: %@", date);
ALog(@"Current time: %@", [NSDate dateWithTimeIntervalSinceNow:0]);
ALog(@"Next update time: %@", [date dateByAddingTimeInterval:600]);

And here's what I got:

Last update time is: Sep 22, 2:33 PM
Using timezone: America/New_York (EDT) offset -14400 (Daylight)
Last updated time: 1970-09-22 18:33:00 +0000
Current time: 2011-09-22 18:43:05 +0000
Next update time: 1970-09-22 18:43:00 +0000

I understand NSLog (my ALog) doesn't care about timezoon, so by displaying it as GMT timezoon is fine, but how can I make the formatter think that what I have Sep 22, 2:33 PM is for current year? I have [dateFormatter setLenient:YES]; but it doesn't work.

Thanks!


What do you think about this:

NSString *str = [NSString stringWithFormat:@"2011 %@", [[summarydict objectForKey:@"root"]objectForKey:@"date_generated"]];
NSLog(@"Last update time is: %@", str);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLenient:YES];
[dateFormatter setDateFormat:@"yyyy MM dd, h:mm a"];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"America/New_York"]];
NSDate *date = [dateFormatter dateFromString:str];
NSLog(@"Using timezone: %@", [dateFormatter timeZone]);
NSLog(@"Last updated time: %@", date);
NSLog(@"Current time: %@", [NSDate dateWithTimeIntervalSinceNow:0]);
NSLog(@"Next update time: %@", [date dateByAddingTimeInterval:600]);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜