我想要显示一个倒数计时器。我有开始日期和结束日期。我需要显示剩余的时间,如
天:小时:分钟:秒
我从这个网站获得了一些代码,但是在结束日期过后它会显示负号。 请任何人帮助我。
-(void) viewWillAppear:(BOOL)animated
{
timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];
}
-(void) updateCountdown
{
NSString *dateString = @"14-12-2012";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *componentsHours = [calendar components:NSHourCalendarUnit fromDate:now];
NSDateComponents *componentMint = [calendar components:NSMinuteCalendarUnit fromDate:now];
NSDateComponents *componentSec = [calendar components:NSSecondCalendarUnit fromDate:now];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *componentsDaysDiff = [gregorianCalendar components:NSDayCalendarUnit
fromDate:now
toDate:dateFromString
options:0];
lblDaysSetting.text=[NSString stringWithFormat:@"%02d",componentsDaysDiff.day];
lblHouresSetting.text=[NSString stringWithFormat:@"%02d",(24-componentsHours.hour)];
lblMinitSetting.text=[NSString stringWithFormat:@"%02d",(60-componentMint.minute)];
lblSecSetting.text=[NSString stringWithFormat:@"%02d",(60-componentSec.second)];
}
答案 0 :(得分:0)
使用以下代码查找两个日期之间的差异:
NSDate *lastDate = fromDate;
NSDate *todaysDate = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:NSDayCalendarUnit fromDate:lastDate toDate:todaysDate options:0];
int days = [comps day];
int minute = [comps minute];
int hour = [comps hour];
int second = [comps second];
答案 1 :(得分:0)
试试这个:
if(componentsDayDiff.day < 0) { //DOUBLE CHECK THIS WITH NSLOG, I DON'T KNOW WHICH ONE WILL BE NEGATIVE, BUT ONE OF THEM WILL
[timer invalidate]; //Stop the timer, it's not needed anymore
//Not _technically_ needed, but a good thing to have, format as you see fit
lblDaysSetting.text = @"0";
lblHouresSetting.text = @"0";
lblMinitSetting.text = @"0";
lblSecSetting.text = @"0";
//[self done] //call whatever method you want when the countdown is complete.
} else {
lblDaysSetting.text=[NSString stringWithFormat:@"%02d",componentsDaysDiff.day];
lblHouresSetting.text=[NSString stringWithFormat:@"%02d",(24-componentsHours.hour)];
lblMinitSetting.text=[NSString stringWithFormat:@"%02d",(60-componentMint.minute)];
lblSecSetting.text=[NSString stringWithFormat:@"%02d",(60-componentSec.second)];
}