我想显示一个倒数计时器。我有开始日期和结束日期。我需要显示剩余时间
天:时:分:秒
我从这个站点得到了一些代码,但是当结束日期过去时它会显示负号。请任何人帮助我。
-(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)];
}