我正在使用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年-1个月0天-2小时..就像为什么那里有( - )?谢谢!
答案 0 :(得分:1)
[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];
您正在进入
然后你有
[NSString stringWithFormat:@"%ld Months %ld Days %ld Hours %ld Minutes %ld Seconds", (long)days, (long)months, (long)hours, (long)minutes, (long)seconds];
您正在进入