我有两次...一个直接取为字符串(@“21:00”),其他是当前时间。我想显示一个倒数计时器,显示从现在开始到21:00的剩余时间。
例如:如果当前时间是17:30,我使用的标签应显示“你还有3小时30分钟......”。 感谢..
答案 0 :(得分:9)
确定已完全修改了我的答案,并创建了问题的完整解决方案,并在github上提供了经过全面测试的示例代码。
享受:)
答案 1 :(得分:3)
这样的事情应该这样做。这将为您提供以秒为单位的剩余时间。然后你只需要标准计时器的东西,如其他答案中所示。
//assumption: targetTime is after now
NSString *targetTime = @"21:00";
//split our time into components
NSArray *timeSplit = [targetTime componentsSeparatedByString:@":"];
NSUInteger hours = [[timeSplit objectAtIndex:0] intValue];
NSUInteger minutes = [[timeSplit objectAtIndex:1] intValue];
NSDate *now = [NSDate date];
//split now into year month day components
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [currentCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:now];
//set our time components from above
[dateComponents setHour:hours];
[dateComponents setMinute:minutes];
NSDate *targetDate = [currentCalendar dateFromComponents:dateComponents];
//ensure target is after now
if ([targetDate timeIntervalSinceDate:now] < 0)
{
NSDateComponents *day = [[NSDateComponents alloc] init];
[day setDay:1];
targetDate = [currentCalendar dateByAddingComponents:day toDate:targetDate options:0];
}
NSTimeInterval timeRemaining = [targetDate timeIntervalSinceDate:now];
答案 2 :(得分:0)
您创建一个每秒触发的NSTimer:
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(tickClock) userInfo:nil repeats:YES];
当它触发时,您输入一个方法:
- (void)tickClock;
在那里,您将日期与当前日期[NSData currentDate]
进行比较;
像
NSTimeInterval distanceBetweenDates = [currentDate timeIntervalSinceDate:yourDate];
其中distanceBetweenDates以秒为单位指定。
要从字符串创建日期,请相应地创建NSDate
NSInteger year = 2011;
NSInteger month = 8;
NSInteger day = 26;
NSInteger hour = 21;
NSInteger minute = 0;
NSInteger second = 0;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:year];
[components setMonth:month];
[components setDay:day];
[components setHour:hour];
[components setMinute:minute];
[components setSecond:second];
NSDate *date = [calendar dateFromComponents:components];
[components release];