【发布时间】:2014-09-08 02:51:05
【问题描述】:
我正在使用NSDate 和NSDateFormatter 创建一个特定日期的倒数计时器。唯一的问题是,当我以不同的格式运行代码时,日期会混乱。这是运行良好的原始代码。
- (void)updateCountdown {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-dd"];
NSDate *startingDate = [dateFormatter dateFromString:@"2014-10-08"];
NSDate *endingDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:startingDate toDate:endingDate options:0];
NSInteger days = [dateComponents day];
NSInteger months = [dateComponents month];
NSInteger years = [dateComponents year];
NSInteger hours = [dateComponents hour];
NSInteger minutes = [dateComponents minute];
NSInteger seconds = [dateComponents second];
NSString *countdownText = [NSString stringWithFormat:@"%ld Years %ld Months %ld Days %ld Hours %ld Minutes %ld Seconds", (long)days, (long)months, (long)years, (long)hours, (long)minutes, (long)seconds];
_countdown.text = countdownText;
[self performSelector:@selector(updateCountdown) withObject:nil afterDelay:1];
}
但是说我想删除年份,所以我像这样更改代码:
- (void)updateCountdown {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-dd"];
NSDate *startingDate = [dateFormatter dateFromString:@"2014-10-08"];
NSDate *endingDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:startingDate toDate:endingDate options:0];
NSInteger days = [dateComponents day];
NSInteger months = [dateComponents month];
NSInteger hours = [dateComponents hour];
NSInteger minutes = [dateComponents minute];
NSInteger seconds = [dateComponents second];
NSString *countdownText = [NSString stringWithFormat:@"%ld Months %ld Days %ld Hours %ld Minutes %ld Seconds", (long)days, (long)months, (long)hours, (long)minutes, (long)seconds];
_countdown.text = countdownText;
[self performSelector:@selector(updateCountdown) withObject:nil afterDelay:1];
}
现在突然间,数据被整整一个月搞砸了。我该如何解决这个问题?
还有为什么输出 0 years -1months 0 days -2 Hours .. 就像为什么那里有 (-) 一样?谢谢!
【问题讨论】:
标签: objective-c format nsdate countdown