如何获得当前剩余时间完成小时?
我想知道还有多少秒钟才能完成一个小时。无论现在是几点?如何获得当前剩余时间完成小时?
如果它05:01:00那么它应该给3540秒 ,如果它的11:58:40那么它会给出80秒等等。我试图在谷歌上找到它,但无法找到它。 在此先感谢。
NSCalendar
得到了方法做那种日期数学(你必须确保处理它是午夜以后虽然如此!):
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
// find next date where the minutes are zero
NSDate *nextHour = [calendar nextDateAfterDate:now matchingUnit:NSCalendarUnitMinute value:0 options:NSCalendarMatchNextTime];
// get the number of seconds between now and next hour
NSDateComponents *componentsToNextHour = [calendar components:NSCalendarUnitSecond fromDate:now toDate:nextHour options:0];
NSLog(@"%ld", componentsToNextHour.second);
非常感谢和高度赞赏 –
NSDate *date1 = [NSDate dateWithString:@"2010-01-01 00:00:00 +0000"];
NSDate *date2 = [NSDate dateWithString:@"2010-02-03 00:00:00 +0000"];
NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
中填写正确的时间和日期,以获得在几秒钟之差
编辑:另一种方法是制定出currentHour的,并返回一个整数。然后添加一个到NSInteger的返回如下
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger currentHour = [components hour];
我不知道这两个时间,我只知道当前的时间,我必须找出需要多少秒完成那个小时? –
http://developer.apple.com/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html#//apple_ref/doc/uid/10000039 – stevenpcurtis
返回当前小时,然后计算当前小时+ 1-(NSInteger)currentHour { //实际上,这些调用可以结合使用 NSDate * now = [NSDate date]; NSCalendar * calendar = [NSCalendar currentCalendar]; NSDateComponents *组件= [日历组件:NSHourCalendarUnit fromDate:now]; return [组件小时]; } – stevenpcurtis
@Vadian的回答非常好。 (投票)
但它需要iOS 8或更高版本。
还有其他方法可以使用NSCalendar
和NSDateComponents
这样的方法来处理较旧的操作系统版本。
您可以使用componentsFromDate
从当前日期获取月份,日期,年份和小时,然后递增小时值并使用方法dateFromComponents:
将您的调整组件转换回日期。
如果恰好在一小时的时间内打电话,您想要做什么?返回当前小时或下一小时,这将在60分钟后完成? –