4
self.dateFormatter = [[NSDateFormatter alloc] init];
[self.dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[self.dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[self.dateFormatter setDateFormat:@"yyyyMMdd"];

NSDate *date = [NSDate date];
NSString *dateString = [self.dateFormatter stringFromDate:date];

此代码有时会为我返回不正确的日期,例如 201300090005。我不明白为什么。

4

1 回答 1

0

我试过这样的东西,但它对我来说总是很好:-

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init]autorelease];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[dateFormatter setDateFormat:@"yyyyMMdd"];

NSDate *date = [NSDate date];
NSString *dateString = [dateFormatter stringFromDate:date];
NSLog(@"yourDateString=%@",dateString);
于 2013-10-18T10:52:31.940 回答